NHibernate Overview

Introduction

NHibernate is a popular open-source .Net ORM. It is based on the popular Java ORM framework and built on top of ADO.NET. Its current version is 4.0.3 and can be installed using the Nuget manager within Visual Studio. It can be used with many databases like SQL Server, Oracle, DB2, Firebird, Informix, Ingres, MySQL, PostgreSQL, SQLite, SQL Server CE and many other.

Let me provide a summary of this tutorial. It contains:

  1. Creating the simple WebAPI project.
  2. Installing of the NHibernate using the Package Manager console.
  3. Defining a simple business object.
  4. Creating a NHibernate Mapper class to load and save the business object.
  5. Configure the NHibernate to link with the database.
  6. Writing simple CURD operations.

Create WebAPI Project

Create a simple web API project named NHibernate Example.

simple web API

Create a Database

Create a database named NHibernateExample and add a table with the name “User”.

table

Create a Business Object

Create a class user as in the following:

  1. public class User  
  2. {  
  3.    public virtual int Id { getset; }  
  4.    public virtual String FirstName { getset; }  
  5.    public virtual String LastName { getset; }  
  6.   
  7. }  
Create a NHibernate Mapper class to load and save the business object as in the following:
  1. public class UserMap: ClassMapping < User > {  
  2.   
  3.     public UserMap() {  
  4.         Schema("[dbo]");  
  5.         Table("[User]");  
  6.         Id(i = > i.Id, map = > map.Generator(Generators.GuidComb));  
  7.         Property(x = > x.FirstName, m = > {  
  8.             m.NotNullable(true);  
  9.         });  
  10.         Property(x = > x.LastName, m = > {  
  11.             m.NotNullable(true);  
  12.         });  
  13.   
  14.     }  
  15.   
  16. }  
Configure the NHibernate to link with Database

Create a class with the name ConfigurationManager.
  1. public static class ConfigurationManager {  
  2.   
  3.     public static Configuration SetConfiguration() {  
  4.         var mapper = new ModelMapper();  
  5.         var config = new Configuration();  
  6.         mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());  
  7.         config.DataBaseIntegration(x = > {  
  8.             x.ConnectionString = "Data Source=U6031005-TPL-A;Initial Catalog=NHibernateExample;Integrated Security=True";  
  9.             x.Driver < SqlClientDriver > ();  
  10.             x.Dialect < MsSql2008Dialect > ();  
  11.         });  
  12.         config.AddAssembly(Assembly.GetExecutingAssembly());  
  13.         config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());  
  14.         return config;  
  15.     }  
  16. }  
Writing simple CURD operations

Create a DataAccess class DALUser.
  1. public class DalUser: IDALUser {  
  2.     private ISessionFactory sessionFactory;  
  3.   
  4.     public DalUser() {  
  5.         var config = ConfigurationManager.SetConfiguration();  
  6.         sessionFactory = config.BuildSessionFactory();  
  7.     }  
  8.   
  9.     public List < User > UserList() {  
  10.         var userList = new List < User > ();  
  11.         using(var session = sessionFactory.OpenSession()) {  
  12.             using(var tx = session.BeginTransaction()) {  
  13.                 userList = session.Query < User > ().ToList();  
  14.                 tx.Commit();  
  15.             }  
  16.         }  
  17.   
  18.         return userList;  
  19.     }  
  20.   
  21. }  
Create a Business class
  1. public class BLUser: IBLUser {  
  2.     public List < User > UserList() {  
  3.         IDALUser dalUser = new DalUser();  
  4.         return dalUser.UserList();  
  5.     }  
  6. }  
Create a Controller class
  1. [RoutePrefix("User")]  
  2. public class UserController: ApiController {  
  3.     [Route("UserList")]  
  4.     public IHttpActionResult getUserList() {  
  5.         IBLUser blUser = new BLUser();  
  6.         var userlist = blUser.UserList();  
  7.         return Ok(userlist);  
  8.     }  
  9. }  
Output 
  1. http://localhost /User/UserList  
  2.   
  3.   
  4. <ArrayOfUser  
  5.     xmlns:i="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xmlns="http://schemas.datacontract.org/2004/07/TestNHibernate.Models">  
  7.     <User>  
  8.         <FirstName>Rakesh Kumar</FirstName>  
  9.         <Id>1</Id>  
  10.         <LastName>Kotha</LastName>  
  11.     </User>  
  12. </ArrayOfUser>