In this post we are going to learn how we can use NHibernate in ASP.NET MVC application.
NHibernate is also a kind of Object Relational Mapper which is a port of popular Java ORM Hibernate. It provides a framework for mapping an domain model classes to a traditional relational databases. Its give us freedom of writing repetitive ADO.NET code as this will be act as our database layer. Let’s get started with NHibernate.
I am going to use SQL Server 2012 express edition as a database. Following is a table with four fields Id, First Name, Last name, Designation.
Let’s create a ASP.NET MVC project for NHibernate via click on File-> New Project –> ASP.NET MVC 4 web application.
It will install like following.
Here you have got different settings for NHibernate. You need to selected driver class, connection provider as per your database. If you are using other databases like Orcle or MySQL you will have different configuration. ThisNHibernate ORM can work with any databases.
Now we need a xml mapping file between class and model with name “Employee.hbm.xml” like following in Nhibernate folder.
Here you can see I have get a session via OpenSession method and then I have queried database for fetching employee database. Let’s create a new for this you can create this via right lick on view on above method.We are going to create a strongly typed view for this.
Our listing screen is ready once you run project it will fetch data as following.
Now let’s create a create view strongly typed view via right clicking on view and add view.
Once you run this application and click on create new it will load following screen.
Here in first action result I have fetched existing employee via get method of NHibernate session and in second I have fetched and changed the current employee with update details. You can create view for this via right click –>add view like below. I have created a strongly typed view for edit.
Once you run code it will look like following.
You can add view like following via right click on actionresult view.
now once you run this in browser it will look like following.
Here in the above first action result will have the delete confirmation view and another will perform actual delete operation with session delete method.
When you run into the browser it will look like following.
That’s it. It’s very easy to have crud operation with NHibernate. Stay tuned for more.
What is NHibernate:
ORMs(Object Relational Mapper) are quite popular this days. ORM is a mechanism to map database entities to Class entity objects without writing a code for fetching data and write some SQL queries. It automatically generates SQL Query for us and fetch data behalf on us.
NHibernate is also a kind of Object Relational Mapper which is a port of popular Java ORM Hibernate. It provides a framework for mapping an domain model classes to a traditional relational databases. Its give us freedom of writing repetitive ADO.NET code as this will be act as our database layer. Let’s get started with NHibernate.
How to download:
There are two ways you can download this ORM. From nuget package and from the source forge site.
- Nuget - http://www.nuget.org/packages/NHibernate/
- Source Forge-http://sourceforge.net/projects/nhibernate/
Creating a table for CRUD:
Creating ASP.NET MVC project for NHibernate:
Installing NuGet package for NHibernate:
I have installed nuget package from Package Manager console via following Command.
It will install like following.
NHibertnate configuration file:
Nhibernate needs one configuration file for setting database connection and other details. You need to create a file with ‘hibernate.cfg.xml’ in model Nhibernate folder of your application with 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=LocalDatabase;Integrated Security=SSPI; </property> <property name="dialect"> NHibernate.Dialect.MsSql2012Dialect </property> </session-factory> </hibernate-configuration>
Here you have got different settings for NHibernate. You need to selected driver class, connection provider as per your database. If you are using other databases like Orcle or MySQL you will have different configuration. ThisNHibernate ORM can work with any databases.
Creating a model class for NHibernate:
Now it’s time to create model class for our CRUD operations. Following is a code for that. Property name is identical to database table columns.
namespace NhibernateMVC.Models { public class Employee { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string Designation { get; set; } } }
Creating a mapping file between class and table:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="NhibernateMVC" namespace="NhibernateMVC.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="FirstName" /> <property name="LastName" /> <property name="Designation" /> </class> </hibernate-mapping>
Creating a class to open session for NHibernate:
I have created a class in models folder called NHIbernateSession and a static function it to open a session for NHibertnate.
using System.Web; using NHibernate; using NHibernate.Cfg; namespace NhibernateMVC.Models { public class NHibertnateSession { 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(); } } }
Listing:
Now we have our open session method ready its time to write controller code to fetch data from the database. Following is a code for that.
using System; using System.Web.Mvc; using NHibernate; using NHibernate.Linq; using System.Linq; using NhibernateMVC.Models; namespace NhibernateMVC.Controllers { public class EmployeeController : Controller { public ActionResult Index() { using (ISession session = NHibertnateSession.OpenSession()) { var employees = session.Query<Employee>().ToList(); return View(employees); } } } }
Here you can see I have get a session via OpenSession method and then I have queried database for fetching employee database. Let’s create a new for this you can create this via right lick on view on above method.We are going to create a strongly typed view for this.
Our listing screen is ready once you run project it will fetch data as following.
Create/Add:
Now its time to write add employee code. Following is a code I have written for that. Here I have used session.save method to save new employee. First method is for returning a blank view and another method with HttpPost attribute will save the data into the database.
public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Employee emplolyee) { try { using (ISession session = NHibertnateSession.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Save(emplolyee); transaction.Commit(); } } return RedirectToAction("Index"); } catch(Exception exception) { return View(); } }
Now let’s create a create view strongly typed view via right clicking on view and add view.
Once you run this application and click on create new it will load following screen.
Edit/Update:
Now let’s create a edit functionality with NHibernate and ASP.NET MVC. For that I have written two action result method once for loading edit view and another for save data. Following is a code for that.
public ActionResult Edit(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get<Employee>(id); return View(employee); } } [HttpPost] public ActionResult Edit(int id, Employee employee) { try { using (ISession session = NHibertnateSession.OpenSession()) { var employeetoUpdate = session.Get<Employee>(id); employeetoUpdate.Designation = employee.Designation; employeetoUpdate.FirstName = employee.FirstName; employeetoUpdate.LastName = employee.LastName; using (ITransaction transaction = session.BeginTransaction()) { session.Save(employeetoUpdate); transaction.Commit(); } } return RedirectToAction("Index"); } catch { return View(); } }
Here in first action result I have fetched existing employee via get method of NHibernate session and in second I have fetched and changed the current employee with update details. You can create view for this via right click –>add view like below. I have created a strongly typed view for edit.
Once you run code it will look like following.
Details:
Now it’s time to create a detail view where user can see the employee detail. I have written following logic for details view.
public ActionResult Details(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get<Employee>(id); return View(employee); } }
You can add view like following via right click on actionresult view.
now once you run this in browser it will look like following.
Delete:
Now its time to write delete functionality code. Following code I have written for that.
public ActionResult Delete(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get<Employee>(id); return View(employee); } } [HttpPost] public ActionResult Delete(int id, Employee employee) { try { using (ISession session = NHibertnateSession.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Delete(employee); transaction.Commit(); } } return RedirectToAction("Index"); } catch(Exception exception) { return View(); } }
Here in the above first action result will have the delete confirmation view and another will perform actual delete operation with session delete method.
When you run into the browser it will look like following.
That’s it. It’s very easy to have crud operation with NHibernate. Stay tuned for more.
Thanks, it was very helpful for me.
ReplyDeleteYou are welcome
ReplyDeleteThank you sooooooo much!! this helps a lot! i have been looking for a post like this for days! thankyouu
ReplyDeletevery helpful
ReplyDeleteThank you very much
Thx .It help me very much.
ReplyDeleteYou are welcome
ReplyDeleteVery Nice Post. It really helped. Please post some more like mapping several Tables Like Department table or something.
ReplyDeleteThanks. I will post about that in future post
ReplyDeleteThanks. this is exactly what I am looking for.
ReplyDeleteYou are most welcome
Deleteneat and clean code..keep up the good work..great post.
ReplyDeleteNice Post,Thank you.
ReplyDeleteHi, You didn't clarify that add employee in which controller and how to map in the routConfig file
ReplyDeleteThanks.
Employee Controller Naturally... You just need to create action methods only for add/edit/delete
DeleteVery good tutorial, helps to easily get started with NHibernate. Thanks!
ReplyDeletethanks
DeleteThaks for this tutorial. NHibernate is an alternate for entity framework. So, need some more on NHibernet..
ReplyDeleteYou're welcome. Nhibernate is there even before entity framwork!!
DeleteNice Tutorial thank's ! but i was wondering how we manage relations between tables.
ReplyDeletewait for ur reply ;)
thanks for kind words I will write a separate post for this as soon as I got some time.
DeleteThank, was very interesting and also usefully.
ReplyDeletethanks
DeleteThank was interesting and usefully.
ReplyDeleteGreat post, exactly what I'm looking for. Thank you.
ReplyDeleteGood tutorial but I cannot get mine working using my own database. Is there a download link for this project so that I can compare mine to yours?
ReplyDeletecan you send me your email address? I will send you code
DeleteClear, simple, effective. Many thanks
ReplyDeleteThanks
Deleteplease my Create code is not working can you pls help me my email Id is gbemigaakindeji@gmail.com
ReplyDeleteSend me your code!!
Deletehere is my code
ReplyDeleteusing NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HiB;
using System.Collections;
#region
protected void btnInsert_Click(object sender, EventArgs e)
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.AddAssembly("HiB");
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
Employees newUser = new Employees();
newUser.FirstName = txtFirstName.Text;
newUser.SecondName = txtLastName.Text;
newUser.DepId = ddlDeptId.SelectedValue.ToString();
// Tell NHibernate that this object should be saved
session.Save(newUser);
// commit all of the changes to the DB and close the ISession
transaction.Commit();
// Closing the session
session.Close();
}
#endregion
What error you are getting?
Deleteplease give me detail about the relational database one to many mapping through nhibernate as i am new to ORM
ReplyDeleteI will post about that in the future.
DeleteVery Nice tutorial. Can you please create and explain a project using multiple database (SQL Server and Oracle in same project using NHibernate with some stored procedure for insert, update and delete)
ReplyDeleteSure I will write about it in future posts.
DeleteHi great Tutorial. But I have a problem in with saving to the database. my edit and create button are not working I don't know why or is there any method I have to write? because I followed everything step by step and am not getting any error. can u please help.
ReplyDeletecheck your route configuration and also your form submit properties check they are properly configured or not as I have used scaffolding they will created automatically in my case. But if you have used manually then it will create a problem
DeleteGreat post, exactly what I'm looking for. Thank you so much :)
ReplyDeleteThanks Roya
DeleteCan you provide sample for MVC with ORACLE.
ReplyDeleteWill do that in future blog post. But you can easily find that examples on internet
Deletegood one thanks
ReplyDeleteVery nice Code - simple, clear and what i m looking for
ReplyDeleteBut a annotation:
NHibertnateSession ... There might be the letter "t" too much ... That's why I first came to stumble
this is my exception please tell me how to solve this:
ReplyDeleteAn exception of type 'System.InvalidOperationException' occurred in NHibernate.dll but was not handled in user code
in sessionfactory its showing error
ISessionFactory sessionFactory = configuration.BuildSessionFactory();
I'm getting this error, i'm trying to simulate this tuts in vb.net.
ReplyDeleteI've explained it well on stackoverflow: http://stackoverflow.com/questions/26489916/nhibernate-vb-net-mvc-could-not-compile-mapping
I think you have already got answered it on stackoverflow. This is because of there is namespace problem in your VB.NET Code.
DeleteI have this error : in list datas
ReplyDeleteLinha 41: @foreach (var item in Model)
Referência de objeto não definida para uma instância de um objeto.
Whats wrong ?
Your model object is not intialized
Deletehi , please i have on add view the scaffol template part is deactivated i can't choose list... how can do it should instal another framework?
ReplyDeleteNot clear what you want to say. Scaffolding still there. Please write your requirement or error clearly.
DeleteHi Jalpesh, Thanks for great tutorial but i am getting below error when implementing your code.
ReplyDeleteCould not compile the mapping document: C:\MVCSharpArch\MVCSportcalIC\MVCSportcalIC\Models\Nhibernate\Employee.hbm.xml
Much appreciate if you could help me please
There should be some typo in code like suppose in table there a field called name and you have written naem something like this.
DeleteFore more details go to following link.
http://stackoverflow.com/questions/16028204/nhibernate-could-not-compile-the-mapping-document
Thanks bro it worked it was typo mistake ;)
DeleteYou're welcome glad that you have identified.
DeleteGreat... I was struggling behind this, It really helped me... Thank you so much
ReplyDelete