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,
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)
);
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
="1.0"="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
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.
="1.0"="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
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.
namespace Swinkaran.Nhbnt.Web.Controllers
{
public class BookController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Your application description page.";
IList<Book> books;
using (ISession session = NHibernateSession.OpenSession())
{
books = session.Query<Book>().ToList();
}
return View(books);
}
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);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Book book = new Book();
book.Title = collection["Title"].ToString();
book.Genre = collection["Genre"].ToString();
book.Author = collection["Author"].ToString();
using (ISession session = NHibernateSession.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(book);
transaction.Commit();
}
}
return RedirectToAction("Index");
}
catch (Exception e)
{
return View();
}
}
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);
}
[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();
using (ISession session = NHibernateSession.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.SaveOrUpdate(book);
transaction.Commit();
}
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Delete(int id)
{
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);
}
[HttpPost]
public ActionResult Delete(long id, FormCollection collection)
{
try
{
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