Click here to Skip to main content
15,880,608 members
Articles / Web Development / HTML

NHibernate – Introduction, configuration & CRUD with MVC

Rate me:
Please Sign up or sign in to vote.
4.80/5 (17 votes)
2 Apr 2017CPOL4 min read 62.7K   2.1K   24   8
This practice demonstrates the basics of NHibernate and shows how to integrate NHibernate into .Net & MVC environment with an example CRUD application

Introduction

This tutorial is more of a practical exercise of how to get the NHibernate framework included to the MVC6 .Net environment and the demonstration will include the following parts:

  • Installing NHibernate
  • Defining a simple business object class.
  • Create an NHibernate mapping to load and save the business object.
  • Configure NHibernate to talk to the database.
  • Writing simple CRUD code in MVC project

The sample project

The sample MVC 6 project I will be creating, contains a single table in SQL sever local DB and we will perform CRUD operation using the NHibernate. (Scope of this tutorial is to setup and environment with MVC 6 and NHibernate, hence in order to keep it simple, we will be having a single table with no relationship.) This solution is a single project and the MVC- controller accesses the NHibernate directly, which may not be suggeted in real projects.

Background

Introduction to NHibernate

NHibernate is an open source object relational mapping technology for .Net Framework.  It provides the framework required for mapping domain model(classes) to a traditional relational databases and generate queries. To read more about NHibernate http://nhibernate.info/

In this article I am focussing more on NHibernate and how it can be include in MVC. Knowledge of .Net and MVC is required before proceeding with this tutorial

Using the code

Database

Create a new database in SQL Server local db, named BookStoreDB. Create a table called Book as shown below,

SQL
CREATE TABLE [dbo].[Book] (
    [Id]          BIGINT        IDENTITY (1, 1) NOT NULL,
    [Title]       VARCHAR (50)  NULL,
    [Author]      VARCHAR (50)  NULL,
    [Genre]       VARCHAR (50)  NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

NHibernate sample table

Create the Project

Let’s start with creating a project in Visual studio. Add an ASP.Net Web application project with MVC template, named Swinkaran.Nhbnt.Web. Throughout this tutorial we will add new libraries and files. Following screenshot shows the files those will be added to the project, later in this tutorial we will talk about each of these file.

 

Installing NHibernate

Now, we have crated aNHibernate can be installed using the NuGet package. There are different ways to install NuGet .Net framework. I will show two most common practices for installing Nhibernare via NuGet.

1. NuGet package manager

Go to NuGet package manager and install as shown below,

2. Package manager console

Go to the package manager console and type the following

PM> install-package NHibernate

To read more about the NuGet package and installation got to NuGet documentation https://docs.microsoft.com/en-us/nuget/guides/install-nuget

Other than above method using NuGet package, developers can also be downloaded the NHibernate libraries from the http://nhibernate.info/.

That’s it. We are now done with including the NHibernate into our MVC6 project.

Creating the NHibernate configuration file

Now, we have created the database and tables, Installed the necesary librarries to work on NHibernate. Lets wire up the .Net application to the database, so that the application can connect to the database. I am using the NHibernate configuration file to achieve this. This configuration file contains the information required to connect the application to the database.

Create a XML or config file under the Models folder, named hibernate.cfg.xml

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

Creating the model class

Create a class, named Book under the Models folder

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

namespace Swinkaran.Nhbnt.Web.Models
{
    public class Book
    {
        public virtual long Id { get; set; }
        public virtual string Title { get; set; }
        public virtual string Author { get; set; }
        public virtual string Genre { get; set; }
    }
}

Creating the mapping file

Create a folder called Mappings and create a new xml file, name it Book.hbm.xml. It is important to have the hbm as it is a part of the file name, which denotes that this file is a mapping file. Define "Embedded Resource" as Build Action for this xml file. The purpose of this file is to create a mapping between the model class and the respective table in the database.

XML
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="Swinkaran.Nhbnt.Web" namespace="Swinkaran.Nhbnt.Web.Models">
  <class name="Book" table="Book" dynamic-update="true" >
    <cache usage="read-write"/>
    <id name="Id" column="Id" type="long">
      <generator class="native" />
    </id>

    <property name="Title"  />
    <property name="Author" />
    <property name="Genre" />
  </class>
</hibernate-mapping>

Managing NHibernate session

Create a class called NhibernateSession.cs

C#
namespace Swinkaran.Nhbnt.Web
{
    public class NHibernateSession
    {
        public static ISession OpenSession()
        {
            var configuration = new Configuration();
            var configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\hibernate.cfg.xml");
            configuration.Configure(configurationPath);
            var bookConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Mappings\Book.hbm.xml");
            configuration.AddFile(bookConfigurationFile);
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();
            return sessionFactory.OpenSession();
        }
    }
}

Adding the Controller

Add a new controller called BookController. The BookController is very simple and basic. This has the methods defined to perform Create, Read, Update and Delete functions on the Book entity. Each of this method make use of the NHibernate session to initialize and open a session and perfom the necessary transaction.

C#
namespace Swinkaran.Nhbnt.Web.Controllers
{
    public class BookController : Controller
    {
        // GET: Book
        public ActionResult Index()
        {
            ViewBag.Message = "Your application description page.";
            IList<Book> books;

            using (ISession session = NHibernateSession.OpenSession())  // Open a session to conect to the database
            {
                books = session.Query<Book>().ToList(); //  Querying to get all the books
            }

            return View(books);
        }

        // GET: Book/Details/5
        public ActionResult Details(int id)
        {
            Book book = new Book();
            using (ISession session = NHibernateSession.OpenSession())
            {
                book = session.Query<Book>().Where(b => b.Id == id).FirstOrDefault();
            }

            return View(book);
        }

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

        // POST: Book/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Book book = new Book();     //  Creating a new instance of the Book
                book.Title = collection["Title"].ToString();
                book.Genre = collection["Genre"].ToString();
                book.Author = collection["Author"].ToString();

                // TODO: Add insert logic here
                using (ISession session = NHibernateSession.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())   //  Begin a transaction
                    {
                        session.Save(book); //  Save the book in session
                        transaction.Commit();   //  Commit the changes to the database
                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return View();
            }
        }

        // GET: Book/Edit/5
        public ActionResult Edit(int id)
        {
            Book book = new Book();
            using (ISession session = NHibernateSession.OpenSession())
            {
                book = session.Query<Book>().Where(b => b.Id == id).FirstOrDefault();
            }

            ViewBag.SubmitAction = "Save";
            return View(book);
        }

        // POST: Book/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                Book book = new Book();
                book.Id = id;
                book.Title = collection["Title"].ToString();
                book.Genre = collection["Genre"].ToString();
                book.Author = collection["Author"].ToString();


                // TODO: Add insert logic here
                using (ISession session = NHibernateSession.OpenSession())
                {
                    using (ITransaction transaction = session.BeginTransaction())
                    {
                        session.SaveOrUpdate(book);
                        transaction.Commit();
                    }
                }
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Book/Delete/5
        public ActionResult Delete(int id)
        {
            // Delete the book
            Book book = new Book();
            using (ISession session = NHibernateSession.OpenSession())
            {
                book = session.Query<Book>().Where(b => b.Id == id).FirstOrDefault();
            }
            ViewBag.SubmitAction = "Confirm delete";
            return View("Edit", book);
        }

        // POST: Book/Delete/5
        [HttpPost]
        public ActionResult Delete(long id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
                using (ISession session = NHibernateSession.OpenSession())
                {
                    Book book = session.Get<Book>(id);

                    using (ITransaction trans = session.BeginTransaction())
                    {
                        session.Delete(book);
                        trans.Commit();
                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return View();
            }
        }
    }
}

The BookController class demonstrates how to perform CRUD using already created NHibernae session. 

Following is the output project. Well, I didnt spend much time on explaining on how to create each views and style settings as this is very basic MVC6 project. However, the downloadable file has all the necesasry source files including completed MVC6 project and styles as shown in below output.

History

Initial version : 02/04/2017

Source code included : 03/04/2017 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Risk Wizard
Australia Australia
Swinkaran Alias Srikaran N Sarma

Comments and Discussions

 
QuestionWhy not Dapper ORM it is faster than NHibernate Pin
Saineshwar Bageri13-May-17 18:49
Saineshwar Bageri13-May-17 18:49 
AnswerRe: Why not Dapper ORM it is faster than NHibernate Pin
Swinkaran13-May-17 22:06
professionalSwinkaran13-May-17 22:06 
GeneralRe: Why not Dapper ORM it is faster than NHibernate Pin
Saineshwar Bageri14-May-17 0:12
Saineshwar Bageri14-May-17 0:12 
GeneralMy vote of 5 Pin
Shmeenimal11-Apr-17 1:24
Shmeenimal11-Apr-17 1:24 
SuggestionSome notes about your article Pin
Klaus Luedenscheidt2-Apr-17 20:22
Klaus Luedenscheidt2-Apr-17 20:22 
GeneralRe: Some notes about your article Pin
Vijay Gill3-Apr-17 2:32
professionalVijay Gill3-Apr-17 2:32 
GeneralRe: Some notes about your article Pin
Swinkaran9-Apr-17 13:43
professionalSwinkaran9-Apr-17 13:43 
GeneralRe: Some notes about your article Pin
Swinkaran9-Apr-17 13:42
professionalSwinkaran9-Apr-17 13:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.