CRUD Operations Using NHibernate with ASP.NET MVC 5

Posted By: Ajay Saptaputre, 18 Oct,2015 Total View : 7874
submit to reddit

In my previous article I discuss about create CRUD operation using Scaffolding with ASP.NET MVC 5 and database first approach using ASP.NET MVC 5 and Entity Framework 6 and model first approach using ASP.NET MVC 5 and Entity Framework 6 using Entity Framework 6.

In this article I am going to discuss how to create CRUD operations like create, retrieve, update and delete using NHibernate with ASP.NET MVC 5 application. Usually in data centric web application, we often creates Data Access Layer (DAL) to perform CRUD operation on physical data store. In order to create DAL, you need to create business object that maps with physical data table columns, writes business logic, write stored procedures to pull the data and save data into the database, store retrieved data into the DataSet or DataTable object. It's tedious and time consuming process. NHibernate act as a data access layer and does everything that like querying data, fetch data, save data etc. Before starting sample application let's first understand what is NHibernate?

What is NHibernate?

NHibernate is an object relation mapping (ORM) for Microsoft .Net platform. NHibernate is complete framework that is used to mapping an object oriented business object to a traditional relational database like SQL Server etc. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks. NHibernate make developers life easy and provide freedom from writing repetitive ADO.NET code. It also addresses the well-known problem like data "object persistence". NHibernate act as data access layer and does everything that like querying data, fetch data, save data etc. NHibernate manage data access transparently, exposing a relatively simple API that can load or save an entire object graph with a line or two of code. NHibernate is free as open source software that is distributed under the GNU Lesser General Public License.

Before creating ASP.NET MVC 5 application using NHibernate let's first create database table with columns and insert some data. This table would be used to save the employee information.

CREATE TABLE [tblEmployee](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[FullName] [varchar](50) NULL,
	[Designation] [varchar](100) NULL,
	[Gender] [varchar](10) NULL,
	[JoinDate] [date] NULL,
	[Salary] [float] NULL,
	[City] [varchar](50) NULL,
	[State] [varchar](50) NULL,
	[Zip] [int] NULL
 CONSTRAINT [PK_tblEmployee] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now insert some records into the "Employee" table.

INSERT [tblEmployee]([Name],[Designation],[Gender],[Role],[Salary],[City],[State],[Zip]) 
VALUES (N'Devendra S',N'Project Lead',N'Male','Manager',12000,N'Bhopal',N'MP',21323)
INSERT [dbo].[tblEmployee]([Name],[Designation],[Gender],[Role],[Salary],[City],[State],[Zip]) 
VALUES (N'Ram M',N'Engineer IT',N'Male','Developer',8000,N'Indore',N'MP',23333)
INSERT [dbo].[tblEmployee]([Name],[Designation],[Gender],[Role],[Salary],[City],[State],[Zip]) 
VALUES (N'Manish S',N'Manager',N'Male','QA',9000,N'Delhi',N'Delhi',32334)
INSERT [dbo].[tblEmployee]([Name],[Designation],[Gender],[Role],[Salary],[City],[State],[Zip]) 
VALUES (N'Rahul E',N'Software Engineer',N'Male','Tech Lead',12000,N'Indore',N'AP',45654)

Step 1: Start Visual studio 2013, click on "New" Project from "File" menu and select "Web" and then "ASP.NET web application" from "New Project". I am selecting .Net framework 4.5 to build this sample application. Now give proper name to the application, I am saying "MVCCustomObject" now click "Ok" button as below screen shot illustrate:

Step 2: Once done, you will see another window which asked to select "Template". Select "Empty" and click on "Ok" button as bellow screen shot illustrate:

Step 3: In order to use NHibernate in your project, you need to add NHibernate (If you have not installed on your system) from "Manage NuGet Packages...". To precede this, right click on your project and select "Manage NuGet Packages..." from menu.

Step 4: From "Manage NuGet Packages" dialog box select "Online" option and then type "NHibernate" from search text box and click on "Install" button after search result display. Now search for ASP.NET MVC, it will search MVC 5 version now click "Install" button. This will installed all the require DLL references to the project. Click "Close" button. This will install all require DLL references in your project

Step 5: Now, right click on "Models" folder and then "Add" than "Add Folder" option. In this sample application I renamed folder as "NHibernate".

Step 6: In order to specify connection string, driver name and provider you needs configuration file. You need to add one file in "NHibernate" folder as "nhibernate.configuration.xml". You need to provide driver class, connection provider as per your database. In this sample ASP.NET MVC 5 application I am using SQL Server 2008. You can use any other database (with different configuration), NHibernate ORM can work with any databases. Notice that I am setting driver class, connection provider as per database selection in configuration file. The "nhibernate.configuration.xml" file contains following details.

<?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=(local);database=MyTestDB;Integrated Security=SSPI;
    </property>
    <property name="dialect">
      NHibernate.Dialect.MsSql2012Dialect
    </property>
  </session-factory>
</hibernate-configuration>

Step 7: Now we need model class with required properties that will maps with database table. So right click on "Models" folder and add new class. In this example I am creating "Employee" class with below properties. See below code snippet:

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

namespace MVCNHibernate.Models
{
    public class Employee
    {
        public virtual int? Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Designation { get; set; }
        public virtual string Role { get; set; }
        public virtual string Gender { get; set; }
        public virtual double Salary { get; set; }
        public virtual string City { get; set; }
        public virtual string State { get; set; }
        public virtual string Zip { get; set; }
        public virtual string Address { get; set; }
    }
}

Step 8: To map model class, you need another mapping file to add in "NHibernate" folder. So, right click on "NHibernate" folder and add another xml file as "Employee.mapping.xml". Notice here, I am specifying "Employee" as class name and database table name "tblEmployee". Also, configure all the "Employee" class properties here. The "Employee.mapping.xml" file contains following details.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" 
assembly="MVCNHibernate" namespace="MVCNHibernate.Models">
  <class name="Employee" table="tblEmployee" dynamic-update="true" >
    <cache usage="read-write"/>
    <id name="Id" column="Id" type="int">
      <generator class="native" />
    </id>
    <property name="Name" />
    <property name="Designation" />
    <property name="Role" />
    <property name="Gender" />
    <property name="Salary" />
    <property name="City" />
    <property name="State" />
    <property name="Zip" />
    <property name="Address" />
  </class>
</hibernate-mapping>

Step 9: In order to open session for "NHibertnate" you need to create another class file with static function. So, right click on "Models" folder and add new class file as "OpenNHibertnateSession.cs". See below code snippet:

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

namespace MVCNHibernate.Models
{
public class OpenNHibertnateSession
{
	public static ISession OpenSession()
	{
		var configuration = new Configuration();
		var configurationPath = HttpContext.Current.Server.MapPath
		(@"~\Models\Nhibernate\nhibernate.configuration.xml");
		configuration.Configure(configurationPath);
		var employeeConfigurationFile = HttpContext.Current.Server.MapPath
		(@"~\Models\Nhibernate\Employee.mapping.xml");
		configuration.AddFile(employeeConfigurationFile);
		ISessionFactory sessionFactory = configuration.BuildSessionFactory();
		return sessionFactory.OpenSession();
	}
}
}

Step 10: Now go to your ASP.NET MVC project and right click on "Controllers" folder and select empty from options, give controller name as "EmployeeController" and click "Add" button. Add below code to "EmployeeController.cs" file.

using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCNHibernate.Models;
using NHibernate.Linq;

namespace MVCNHibernate.Controllers
{
    public class EmployeeController : Controller
    {

        public ActionResult Index()
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                var employees = session.Query().ToList();
                return View(employees);
            }
        }

        public ActionResult Details(int id = 0)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                var employee = session.Get(id);
                return View(employee);
            }
        }

        //
        // GET: /Associates/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Associates/Create
        [HttpPost]
        public ActionResult Create(Employee emp)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(emp);
                    transaction.Commit();
                }
            }

            return View(emp);
        }

        //
        // GET: /Associates/Edit/5
        public ActionResult Edit(int id = 0)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                var employee = session.Get(id);
                return View(employee);
            }
        }

        //
        // POST: /Associates/Edit/5
        [HttpPost]
        public ActionResult Edit(int? id, Employee emp)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                var employee = session.Get(id);
                employee.Name = emp.Name;
                employee.Designation = emp.Designation;
                employee.Role = emp.Role;
                employee.Gender = emp.Gender;
                employee.Salary = emp.Salary;
                employee.City = emp.City;
                employee.State = emp.State;
                employee.Zip = emp.Zip;
                employee.Address = emp.Address;

                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(employee);
                    transaction.Commit();
                }
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /Associates/Delete/5
        public ActionResult Delete(int id = 0)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                var employee = session.Get(id);
                return View(employee);
            }
        }

        //
        // POST: /Associates/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id, Employee emp)
        {
            using (ISession session = OpenNHibertnateSession.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(emp);
                    transaction.Commit();
                }
            }
            return RedirectToAction("Index");
        }
	}
}

Step 11: Notice above code snippet, I have added all the require action methods that will perform complete CRUD operations.

Step 12: Now right click on "Index" action method, select "Add View" and select "List" template from dropdown. To build view you will need to specify model class as "Employee" as below screen shot illustrate. Click "Add" button.

Step 13: In order to create other views for "Details", "Delete", "Create" and "Edit" follow the step 12 and select "Details", "Delete", "Create" and "Edit" templates respectively. This will automatically generate view in "Employee" folder under "Views" folder to render the data and set the model reference in each view page appropriately. Once you create all the views, solution explorer will looks like below screen shot:

Step 14: All right, new run the application and from browser add controller and action method name in URL as bellow. This will display all the employees from database as we are passing to the view.

Step 15: Now click on "Create New" link, you can see below screen that allows you to add new employee. Similarly you can perform any operation like edit, delete and update.

Download Code ⇩

Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

 
 
SHARE THIS IF YOU LIKE!
submit to reddit
SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.