Fluent Nhibernate Sample Project in Asp.net MVC

Nhibernate is an ORM designed for Microsoft.Net, it's free and open source and it's a port of java mapper to Dot Net. And fluent Nhibernate is a separate version of Nhibernate which lets you write your entities according to your business instead of starting from creating tables, fluent Nhibernate is just a fluent API for mapping classes with NHibernate. what an ORM does, is persisting object In database and then retrieving when it is needed, indeed it translates the object to database and vice versa.

In Entity Framework you use DbContext or objectContext(in earlier versions) to make configuration, in this case Models or properties acts as a UnitOfWork pattern but In Nhibernate by Using ISessionFactory Models are keep in a separate in-memory database. I'm going to show a simple Nhibernate configuration in this article ,Now let's start!

create a new MVC4 project and get the latest version of Fluent Nhibernate by Nuget:

NH

Or you can go to the web site and get the latest version and reference the Fluent Nhibernate ,now create a new class named Product : 

  1.     public class Product
  2.     {
  3.         public virtual int Id { get; set; }
  4.         public virtual string Name { get; set; }
  5.         public virtual Category Category { get; set; }
  6.     }

 and then add the Category Class to your Model folder in your project :

  1.     public class Category
  2.     {
  3.         public virtual int Id { get; set; }
  4.         public virtual string Name { get; set; }
  5.     }

you should define the properties as virtual because of lazy loading(retrieving an object or so-called data from database when it's needed is lazy loading) ,now create two separate class for mapping this Model classes via Fluent Nhibernate :

  1.     public sealed class ProductMapping : ClassMap<Product>
  2.     {
  3.         public ProductMapping()
  4.         {
  5.             LazyLoad();
  6.             Table("Product");
  7.             Id(p => p.Id);
  8.             Id(p => p.Id).GeneratedBy.Identity();
  9.             Map(p => p.Name);
  10.             References(p => p.Category);
  11.         }
  12.     }
 
  1.     public sealed class CategoryMapping : ClassMap<Category>
  2.     {
  3.         public CategoryMapping()
  4.         {
  5.             LazyLoad();
  6.             Table("Category");
  7.             Id(c => c.Id);
  8.             Id(c => c.Id).GeneratedBy.Identity();
  9.             Map(c => c.Name);
  10.         }
  11.      }

Now the most important and goal of this article is about configuration class of Fluent Nhibernate, create the class with this definition

  1.     public class SessionFactory : IHttpModule
  2.     {
  3.         private static readonly ISessionFactory _SessionFactory;
  4.         static SessionFactory()
  5.         {
  6.             _SessionFactory = CreateSessionFactory();
  7.         }
  8.         public void Init(HttpApplication context)
  9.         {
  10.             context.BeginRequest += BeginRequest;
  11.             context.EndRequest += EndRequest;
  12.         }
  13.  
  14.         public void Dispose()
  15.         {
  16.         }
  17.  
  18.         public static ISession GetCurrentSession()
  19.         {
  20.             return _SessionFactory.GetCurrentSession();
  21.         }
  22.  
  23.         private static void BeginRequest(object sender, EventArgs e)
  24.         {
  25.             ISession session = _SessionFactory.OpenSession();
  26.             session.BeginTransaction();
  27.             CurrentSessionContext.Bind(session);
  28.         }
  29.  
  30.         private static void EndRequest(object sender, EventArgs e)
  31.         {
  32.             ISession session = CurrentSessionContext.Unbind(_SessionFactory);
  33.             if (session == null) return;
  34.             try
  35.             {
  36.                 session.Transaction.Commit();
  37.             }
  38.             catch (Exception)
  39.             {
  40.                 session.Transaction.Rollback();
  41.             }
  42.             finally
  43.             {
  44.                 session.Close();
  45.                 session.Dispose();
  46.             }
  47.         }
  48.  
  49.         private static ISessionFactory CreateSessionFactory()
  50.         {
  51.             return Fluently.Configure()
  52.                            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c =>    c.FromConnectionStringWithKey("DefaultConnection")))
  53.                            .Mappings(m => m.AutoMappings.Add(CreateMappings()))
  54.                            .CurrentSessionContext<WebSessionContext>()
  55.                            .BuildSessionFactory();
  56.         }
  57.  
  58.         private static AutoPersistenceModel CreateMappings()
  59.         {
  60.             return AutoMap
  61.                 .Assembly(System.Reflection.Assembly.GetCallingAssembly())
  62.                 .Where(t => t.Namespace != null && t.Namespace.EndsWith("Models"))
  63.                 .Conventions.Setup(c => c.Add(DefaultCascade.SaveUpdate()));
  64.         }
  65.     }

 

Now Open Web.Config file and set the connectionString tag :

  1. <connectionStrings>
  2.     <add name="DefaultConnection" connectionString="Server=EHSAN\EHSAN;Database=NhMvcDB;Integrated Security=True" providerName="System.Data.SqlClient" />
  3.   </connectionStrings>

Notice that NhMvcDB is my database name and DefaultConnection is my connectionString Name and EHSAN\EHSAN is my SQL server instance name!

You should create the Repository class to talk to database, to make it simple I just create the ProductRepository Class (Not a Generic class for using all entities), to do that add an Interface to your Model :

  1.     public interface IProductRepository
  2.     {
  3.         void Add(Product product);
  4.         Product Get(int id);
  5.         void Remove(Product product);
  6.         IEnumerable<Product> GetAll();
  7.         IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId);
  8.         IEnumerable<Category> GetAllCategoriesQuery();
  9.     }

And then  implement the members in ProductRepository class like this

  1.     public class ProductRepository : IProductRepository
  2.     {
  3.         private readonly ISession _session;
  4.  
  5.         public ProductRepository()
  6.         {
  7.             _session = SessionFactory.GetCurrentSession();
  8.         }
  9.         public void Add(Product product)
  10.         {
  11.             SessionFactory.GetCurrentSession().Save(product);
  12.         }
  13.  
  14.         public Product Get(int id)
  15.         {
  16.             return SessionFactory.GetCurrentSession().Get<Product>(id);
  17.         }
  18.  
  19.         public void Remove(Product product)
  20.         {
  21.             SessionFactory.GetCurrentSession().Delete(product);
  22.         }
  23.  
  24.         public IEnumerable<Product> GetAll()
  25.         {
  26.             return _session.Query<Product>();
  27.         }
  28.  
  29.         public IEnumerable<Product> GetAllProductsByCategoryQuery(int categoryId)
  30.         {
  31.             var products= _session.Query<Product>();
  32.             var productsByCategory = from c in products
  33.                                      where c.Id == categoryId
  34.                                      select c;
  35.             return productsByCategory;
  36.         }
  37.  
  38.         public IEnumerable<Category> GetAllCategoriesQuery()
  39.         {
  40.             return _session.Query<Category>();
  41.         }
  42.     }

Now create the Service interface

  1.     public interface IProductService
  2.     {
  3.         void AddProduct(Product product);
  4.         void RemoveProduct(Product productId);
  5.         Product GetProduct(int productId);
  6.         IEnumerable<Product> GetAllProducts();
  7.         IEnumerable<Product> GetAllProductsByCategory(int categoryId);
  8.         IEnumerable<Category> GetAllCategory();
  9.     }

And Service implementation :

  1.     public class ProductService : IProductService
  2.     {
  3.         private readonly IProductRepository _productRepository;
  4.         public ProductService(IProductRepository productService)
  5.         {
  6.             _productRepository = productService;
  7.         }
  8.         public void AddProduct(Product product)
  9.         {
  10.             _productRepository.Add(product);
  11.         }
  12.         public void RemoveProduct(Product productId)
  13.         {
  14.             _productRepository.Remove(productId);
  15.         }
  16.         public Product GetProduct(int productId)
  17.         {
  18.             var product = new Product { Id = productId };
  19.             return product;
  20.         }
  21.         public IEnumerable<Product> GetAllProducts()
  22.         {
  23.             var products = _productRepository.GetAll();
  24.             return products;
  25.         }
  26.         public IEnumerable<Product> GetAllProductsByCategory(int categoryId)
  27.         {
  28.             var products = _productRepository.GetAllProductsByCategoryQuery(categoryId);
  29.             return products;
  30.         }
  31.         public IEnumerable<Category> GetAllCategory()
  32.         {
  33.             var categories = _productRepository.GetAllCategoriesQuery();
  34.             return categories;
  35.         }
  36.     }
 

 and in Controllers folder create the ProductController with this definition

 

  1.     public class ProductController : Controller
  2.     {
  3.       private readonly IProductService _productService;
  4.  
  5.         public ProductController(IProductService productService)
  6.         {
  7.             _productService = productService;
  8.         }
  9.  
  10.         public ActionResult List()
  11.         {
  12.             var products = _productService.GetAllProducts();
  13.             return View(products);
  14.         }
  15.  
  16.         public ActionResult Add()
  17.         {
  18.             return View();
  19.         }
  20.  
  21.         [HttpPost]
  22.         public ActionResult Add(Product product)
  23.         {
  24.             if (ModelState.IsValid)
  25.             {
  26.                 _productService.AddProduct(product);
  27.             }
  28.             return View();
  29.         }
  30.   }

 

Which list action returns the list of products and by Add action you can add a product , about the Dependency Resolver , add Ninject by Nuget :

 

Nuget

 

Then add this configuration class to you project

  1.     public class NinjectConfig
  2.     {
  3.         private static IKernel _ninjectKernel;
  4.         public class NinjectDependencyResolver : DefaultControllerFactory
  5.         {
  6.             public NinjectDependencyResolver()
  7.             {
  8.                 _ninjectKernel = new StandardKernel();
  9.                 ConfigurDepndency();
  10.             }
  11.             protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  12.             {
  13.                 return controllerType == null ? null : (IController)_ninjectKernel.Get(controllerType);
  14.             }
  15.         }
  16.         private static void ConfigurDepndency()
  17.         {
  18.             _ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
  19.             _ninjectKernel.Bind<IProductService>().To<ProductService>();
  20.         }
  21.     }

 

And add this line of code to your global.asax in Application_Start()

  1.  ControllerBuilder.Current.SetControllerFactory(new NinjectConfig.NinjectDependencyResolver()); 

 end!


Tags: nHibernate C# Asp.Net MVC


comments powered by Disqus