Introduction

  • In my previous blog post I explained how to get NHibernate configured and get it working.
  • In this I’m going to show how to create a NHibernate session factory and using that factory, how to get the CRUD functionality done.


Steps:

1.       First get NHibernate configured in an ASP.Net Web Application.

          Check out my previous blog post: Part I - Getting started with NHibernate

2.       Now create a new class: NHibernateHelper.cs

 using NHibernate;  
 using NHibernate.Cfg;  
 using NHibernate.Context;  
 using System.Web;  
   
 namespace NHibernateWeb  
 {  
   public class NHibernateHelper  
   {  
     private ISessionFactory _sessionFactory = null;  
   
     public ISessionFactory SessionFactory  
     {  
       get  
       {  
         if (_sessionFactory == null)  
         {  
           Configuration configuration = new Configuration();  
           var hibernateConfigurationPath = HttpContext.Current.Server.MapPath(@"~\Models\Config\hibernate.cfg.xml");  
           configuration.Configure(hibernateConfigurationPath);  
           var refCallTypeConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Models\Mappings\UserInfo.hbm.xml");  
           configuration.AddFile(refCallTypeConfigurationFile);  
   
           _sessionFactory = configuration.BuildSessionFactory();  
         }  
   
         return _sessionFactory;  
       }  
     }  
   
     public ISession OpenSession()  
     {  
       return SessionFactory.OpenSession();  
     }  
   
     public void CreateSession()  
     {  
       CurrentSessionContext.Bind(OpenSession());  
     }  
   
     public void CloseSession()  
     {  
       if (CurrentSessionContext.HasBind(SessionFactory))  
       {  
         CurrentSessionContext.Unbind(SessionFactory).Dispose();  
       }  
     }  
   
     public ISession GetCurrentSession()  
     {  
       if (!CurrentSessionContext.HasBind(SessionFactory))  
       {  
         CurrentSessionContext.Bind(SessionFactory.OpenSession());  
       }  
   
       return SessionFactory.GetCurrentSession();  
     }  
   }  
 }  

3.       Now create another new class: SessionHelper.cs

 using NHibernate;  
   
 namespace NHibernateWeb  
 {  
   public class SessionHelper  
   {  
     private NHibernateHelper _nHibernateHelper = null;  
   
     public SessionHelper()  
     {  
       _nHibernateHelper = new NHibernateHelper();  
     }  
   
     public ISession Current  
     {  
       get  
       {  
         return _nHibernateHelper.GetCurrentSession();  
       }  
     }  
   
     public void CreateSession()  
     {  
       _nHibernateHelper.CreateSession();  
     }  
   
     public void ClearSession()  
     {  
       Current.Clear();  
     }  
   
     public void OpenSession()  
     {  
       _nHibernateHelper.OpenSession();  
     }  
   
     public void CloseSession()  
     {  
       _nHibernateHelper.CloseSession();  
     }  
   }  
 }  

4.       To list existing records:
 public void GetAllData()  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         var UserList = CurrentSession.CreateCriteria<UserInfo>().List<UserInfo>();  
   
         foreach (var UserItem in UserList)  
         {  
           string userInfo = string.Format("Id: {0} <br/> Name: {1} <br/> Address: {2} <br/> Phone: {3} <br/> Date Created: {4} <br/><br/>", UserItem.Id, UserItem.Name, UserItem.Address, UserItem.Phone, UserItem.DateCreated.ToShortDateString());  
           Response.Write(userInfo);  
         }  
   
         sessionHelper.CloseSession();  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  

5.       To Insert a record:
 public void InsertRecord(UserInfo userInfo)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         using (ITransaction transaction = CurrentSession.BeginTransaction())  
         {  
           CurrentSession.Save(userInfo);  
           transaction.Commit();  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  


6.         To Update a existing record
 public void UpdateRecordById(int userId, UserInfo userInfo)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         UserInfo existsingUserInfo = CurrentSession.Get<UserInfo>(userId);  
   
         if (existsingUserInfo != null)  
         {  
           existsingUserInfo.Name = userInfo.Name;  
           existsingUserInfo.Address = userInfo.Address;  
           existsingUserInfo.Phone = userInfo.Phone;  
           existsingUserInfo.DateCreated = userInfo.DateCreated;  
   
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Save(existsingUserInfo);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  

7.          To Delete a record
 public void DeleteRecordById(int userId)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         UserInfo existsingUserInfo = CurrentSession.Get<UserInfo>(userId);  
   
         if (existsingUserInfo != null)  
         {  
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Delete(existsingUserInfo);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  

 public void DeleteRecordByQuery(string sql)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         IQuery query = CurrentSession.CreateQuery(sql);  
   
         if (query.List().Count > 0)  
         {  
           UserInfo user = query.List<UserInfo>()[0];  
   
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Delete(user);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  

8.       This is the listing of full code
 using NHibernate;  
 using NHibernate.Cfg;  
 using NHibernateWeb.Models.Classes;  
 using System;  
 using System.Web;  
 using System.Web.UI;  
   
 namespace NHibernateWeb  
 {  
   public partial class _Default : Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       UserInfo userInfo = new UserInfo();  
   
       // insert a new record       
       userInfo.Name = "New User";  
       userInfo.Address = "Melbourne";  
       userInfo.Phone = "0416213195";  
       userInfo.DateCreated = DateTime.Today;  
       InsertRecord(userInfo);  
   
       // update record  
       userInfo.Name = "Sameera Jayalath AUS";  
       userInfo.Address = "Melbourne";  
       userInfo.Phone = "0416213195";  
       userInfo.DateCreated = DateTime.Today;  
       UpdateRecordById(1, userInfo);  
   
       // delete record - by id  
       DeleteRecordById(0);  
   
       // delete record - by query  
       string name = "New User";  
       string sql = "FROM UserInfo WHERE Name = '" + name + "'";  
       DeleteRecordByQuery(sql);  
   
       // get all data  
       GetAllData();  
     }  
   
     public void GetData()  
     {  
       try  
       {  
         var configuration = new Configuration();  
         var hibernateConfigurationPath = HttpContext.Current.Server.MapPath(@"~\Models\Config\hibernate.cfg.xml");  
         configuration.Configure(hibernateConfigurationPath);  
         var refCallTypeConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Models\Mappings\UserInfo.hbm.xml");  
         configuration.AddFile(refCallTypeConfigurationFile);  
         ISessionFactory sessionFactory = configuration.BuildSessionFactory();  
         ISession session = sessionFactory.OpenSession();  
   
         var UserList = session.CreateCriteria<UserInfo>().List<UserInfo>();  
   
         foreach (var UserItem in UserList)  
         {  
           string userInfo = string.Format("Id: {0} <br/> Name: {1} <br/> Address: {2} <br/> Phone: {3} <br/> Date Created: {4} <br/><br/>", UserItem.Id, UserItem.Name, UserItem.Address, UserItem.Phone, UserItem.DateCreated.ToShortDateString());  
           Response.Write(userInfo);  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   
     public void GetAllData()  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         var UserList = CurrentSession.CreateCriteria<UserInfo>().List<UserInfo>();  
   
         foreach (var UserItem in UserList)  
         {  
           string userInfo = string.Format("Id: {0} <br/> Name: {1} <br/> Address: {2} <br/> Phone: {3} <br/> Date Created: {4} <br/><br/>", UserItem.Id, UserItem.Name, UserItem.Address, UserItem.Phone, UserItem.DateCreated.ToShortDateString());  
           Response.Write(userInfo);  
         }  
   
         sessionHelper.CloseSession();  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   
     public void InsertRecord(UserInfo userInfo)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         using (ITransaction transaction = CurrentSession.BeginTransaction())  
         {  
           CurrentSession.Save(userInfo);  
           transaction.Commit();  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   
     public void UpdateRecordById(int userId, UserInfo userInfo)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         UserInfo existsingUserInfo = CurrentSession.Get<UserInfo>(userId);  
   
         if (existsingUserInfo != null)  
         {  
           existsingUserInfo.Name = userInfo.Name;  
           existsingUserInfo.Address = userInfo.Address;  
           existsingUserInfo.Phone = userInfo.Phone;  
           existsingUserInfo.DateCreated = userInfo.DateCreated;  
   
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Save(existsingUserInfo);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   
     public void DeleteRecordById(int userId)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         UserInfo existsingUserInfo = CurrentSession.Get<UserInfo>(userId);  
   
         if (existsingUserInfo != null)  
         {  
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Delete(existsingUserInfo);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   
     public void DeleteRecordByQuery(string sql)  
     {  
       try  
       {  
         SessionHelper sessionHelper = new SessionHelper();  
         sessionHelper.OpenSession();  
         ISession CurrentSession = sessionHelper.Current;  
   
         IQuery query = CurrentSession.CreateQuery(sql);  
   
         if (query.List().Count > 0)  
         {  
           UserInfo user = query.List<UserInfo>()[0];  
   
           using (ITransaction transaction = CurrentSession.BeginTransaction())  
           {  
             CurrentSession.Delete(user);  
             transaction.Commit();  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         Response.Write(ex.ToString());  
       }  
     }  
   }  
 }  

That's it! Enjoy!!

0

Add a comment

In this tutorial I’m going to show how to:
• Create an ASP.NET Core MVC Application and Publish to Azure
• Create/Purchase a Custom Domain from a Custom Domain Provider
• Configure Custom Domain on Azure
Alt Text
You can find the PDF version of this tutorial here.
You can find all my Azure/.Net tutorials here and here.
Enjoy !!
0

Add a comment

About Me
About Me
Blog Archive
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.