Hello Friends, in this tutorial I am going to introduce you about NHibernate in .NET and also we are going to develop an application using NHiberate in ASP.NET MVC.

After completing this session you will be able to understand:

  • What is NHibernate?
  • How to Perform CRUD operation using NHibernate in ASP.NET MVC.

What is NHibernate?

In past, we spent our most of the time in writing and maintaining data access code. This is where we need NHibernate. NHibernate is an open source ORM framework. It is used to create a mapping between your OO application and tables in the database for persistence. NHibernate is used to create a virtual representation of database objects within the code.

You can learn more about ORM here.

Why should we use NHibernate?

We should use NHibernate because of the following reasons:

  • It saves our time from writing repetitive code for data access.
  • Increase developer productivity while performing crud operation.
  • Become essential when developing an application whose purpose is to perform CRUD(Create, Read, Update and Delete) Operation on the database.

NHibernate

Let’s understand more about NHibernate with an application in ASP.NET MVC.

An example of NHibernate:

Let’s Work on the database design first.

Step 1-  Open SQL Server and run the following script.

CREATE DATABASE NHibernateDemo
USE NHibernateDemo
CREATE TABLE [dbo].[Employee]
(
ID INT PRIMARY KEY IDENTITY,
Name VARCHAR(100),
Address VARCHAR(100),
ContactNo VARCHAR(20)
)

 

Step 2- Open Visual Studio and Create an ASP.NET MVC application with the name NHibernateDemo.

NHibernate

Step 3- Right Click on the Controller folder and Create a HomeController.

NHibernate

NHibernate

You will have an HomeController with the following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;




namespace NHibernateDemo.Controllers

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/




        public ActionResult Index()

        {

            return View();

        }




    }

}

 

Step 4- Go to Tools>Library Package Manager>Package Manager Console and run the following command.

NHibernate

Install-Package NHibernate

NHibernate

Step 5- Right Click on the Model folder in Solution Explorer and create a folder with the name NHibernate.

Step 6- For Database Connection and other settings we need to create “hibernate.cfg.xml” file in NHiberate folder that we have just created in Step 5. Right Click on the NHibernate folder inside Model Folder and create a xml file with the name “hibernate.cfg.xml”.

Step 7- Write following code in “hibernate.cfg.xml”.

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

 <session-factory>

 <property name="connection.provider">

 NHibernate.Connection.DriverConnectionProvider

 </property>

 <property name="connection.driver_class">

 NHibernate.Driver.SqlClientDriver

 </property>

 <property name="connection.connection_string">

 Server=DESKTOP-9VC12LL\SQLEXPRESS;database=NHibernateDemo;Integrated Security=true;

 </property>

 <property name="dialect">

 NHibernate.Dialect.MsSql2012Dialect

 </property>

 </session-factory>

</hibernate-configuration>

Change connection string according to your SQL Server configuration here.

 <property name="connection.connection_string">

Server=DESKTOP-9VC12LL\SQLEXPRESS;database=NHibernateDemo;Integrated Security=true;

</property>

 

Step 8- Right Click on the Model folder and create a class with the name Employee class that will be mapped to a Database table.

Step 9- Write the following code in Employee class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NHibernateDemo.Models
{
 public class Employee
 {
 public virtual int ID { get; set; }
 public virtual string Name { get; set; }
 public virtual string Address { get; set; }
 public virtual string ContactNo { get; set; }
 }
}

Step 10- Now we need to create a xml file that will map our domain class to a database table. Right Click on the NHibernate folder inside Model folder and create a xml file with the name Employee.hbm.xml.

Step 11- Write the following code in Employee.hbm.xml file.

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="NHibernateDemo" namespace="NHibernateDemo.Models">

 <class name="Employee" table=" Employee " dynamic-update="true" >

 <cache usage="read-write"/>

 <id name="ID" column="ID" type="int">

 <generator class="native" />

 </id>

 <property name="Name" />

 <property name="Address" />

 <property name="ContactNo" />

 </class>

</hibernate-mapping>

Step 11- Create a class to open session for NHibernate. Right Click on the Model folder and add a class NHibernateSession.

using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NHibernateDemo.Models
{
 public class NHIbernateSession
 {
 public static ISession OpenSession()
 {

 var configuration = new Configuration();

 var configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\Nhibernate\hibernate.cfg.xml");

 configuration.Configure(configurationPath);

 var employeeConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Models\NHibernate\Employee.hbm.xml");

 configuration.AddFile(employeeConfigurationFile);

 ISessionFactory sessionFactory = configuration.BuildSessionFactory();

 return sessionFactory.OpenSession();

 }
 }
}

Step 12- Go to HomeController and modify Index action method as below.

public ActionResult Index()
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

var employee = session.Query<Employee>().ToList();

return View(employee);

}

}

Step 13- Right Click on the Index action method and add an Index View like this.

NHibernate

NHibernate

Choose the option that is circled and click on the Add button.

Step 14- Make sure you have following code in your Index.cshtml file.

@model IEnumerable<NHibernateDemo.Models.Employee>

@{
 ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
 @Html.ActionLink("Create New", "Create")
</p>
<table>
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Name)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Address)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.ContactNo)
 </th>
 <th></th>
 </tr>

@foreach (var item in Model) {
 <tr>
 <td>
 @Html.DisplayFor(modelItem => item.Name)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.Address)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.ContactNo)
 </td>
 <td>
 @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
 
 @Html.ActionLink("Delete", "Delete", new { id=item.ID })
 </td>
 </tr>
}

</table>

Step 15- Define an action method to perform Create Employee operation. Write the following code in HomeController.

public ActionResult Create()
 {

return View();

}

[HttpPost]

public ActionResult Create(Employee objEmployee)
 {

try
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

using (ITransaction transaction = session.BeginTransaction())
 {

session.Save(objEmployee);

transaction.Commit();


 }

}


 return RedirectToAction("Index");

}

catch (Exception exception)
 {

return View();

}

}

Step 16- Right Click on the Create action method and add View like this:

NHibernate

NHibernate

Choose the option that is circled and click on the Add button,

Step 17- Make sure your Create View has the following code.

@model NHibernateDemo.Models.Employee

@{
 ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

<fieldset>
 <legend>Employee</legend>

<div class="editor-label">
 @Html.LabelFor(model => model.Name)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Address)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Address)
 @Html.ValidationMessageFor(model => model.Address)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.ContactNo)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.ContactNo)
 @Html.ValidationMessageFor(model => model.ContactNo)
 </div>

<p>
 <input type="submit" value="Create" />
 </p>
 </fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>


Step 18- To Edit Employee Details add following Action method to the HomeController.

public ActionResult Edit(int ID)
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

var objEmployee = session.Get<Employee>(ID);

return View(objEmployee);

}


 }

[HttpPost]

public ActionResult Edit(int ID, Employee objEmployee)
 {

try
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

var objEmployeeUpdate = session.Get<Employee>(ID);


 objEmployeeUpdate.Name = objEmployee.Name;

objEmployeeUpdate.Address = objEmployee.Address;

objEmployeeUpdate.ContactNo = objEmployee.ContactNo;


 using (ITransaction transaction = session.BeginTransaction())
 {

session.Save(objEmployeeUpdate);

transaction.Commit();


 }

}

return RedirectToAction("Index");

}

catch
 {

return View();

}


 }

Step 19- Add View for Edit Action method. Right Click on the Edit Action method and add a view like this.

NHibernate

NHibernate

Choose the option that is circled and click on the Add button.

Step 20- To Delete Employee add the following Action method to the HomeController.

public ActionResult Delete(int ID)
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

var objEmployee = session.Get<Employee>(ID);

return View(objEmployee);

}

}
 [HttpPost]

public ActionResult Delete(int ID, Employee objEmployee)
 {

try
 {

using (ISession session = NHIbernateSession.OpenSession())
 {

using (ITransaction transaction = session.BeginTransaction())
 {

session.Delete(objEmployee);

transaction.Commit();

}

}

return RedirectToAction("Index");

}

catch (Exception exception)
 {

return View();

}

}

Run the application and check the output

You can download the complete source code from here.

You must also follow the related links.

Hope you have understood about NHhibernate in .NET.

Thank You.

Leave a Comment