Sunday, September 29, 2013

Getting Started with NHibernate and ASP.NET MVC- CRUD Operations

In this post we are going to learn how we can use NHibernate in ASP.NET MVC application.

What is NHibernate:


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.
  1. Nuget - http://www.nuget.org/packages/NHibernate/
  2. Source Forge-http://sourceforge.net/projects/nhibernate/

Creating a table for CRUD:


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.

NhibernateASPNETMVCTable

Creating ASP.NET MVC project for NHibernate:


Let’s create a ASP.NET MVC project for NHibernate via click on File-> New Project –> ASP.NET MVC 4 web application.

NhibernateASPNETMVCProject

Installing NuGet package for NHibernate:


I have installed nuget package from Package Manager console via following Command.

NhibernateNugetPackage

It will install like following.

PackageManagerConsoleNhibernate

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:



Now we need a xml mapping file between class and model with name “Employee.hbm.xml” like following in Nhibernate folder.
<?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.

Getting Started with NHibernate and asp.net mvc

Our listing screen is ready once you run project it will fetch data as following.

EmployeeListingusingNhibernateandaspnetmvc

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.

AddViewwithNhibertnateandaspnetmvc

Once you run this application and click on create new it will load following screen.

AddViewScreenwithNhibernateandaspnetmvc

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.

EditViewwithNhibernateandaspnetmvc

Once you run code it will look like following.

EditViewScreenwithNhibernateandaspnetmvc

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.

Detailsviewwithnhibernateandaspnetmvc

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.

Deleteviewwithaspnetmvcandnhibernate

When you run into the browser it will look like following.

DeleteScreenwithaspnetmvcandnhibernate

That’s it. It’s very easy to have crud operation with NHibernate. Stay tuned for more.
Share:

62 comments:

  1. Thanks, it was very helpful for me.

    ReplyDelete
  2. Thank you sooooooo much!! this helps a lot! i have been looking for a post like this for days! thankyouu

    ReplyDelete
  3. very helpful
    Thank you very much

    ReplyDelete
  4. Thx .It help me very much.

    ReplyDelete
  5. Very Nice Post. It really helped. Please post some more like mapping several Tables Like Department table or something.

    ReplyDelete
  6. Thanks. I will post about that in future post

    ReplyDelete
  7. Thanks. this is exactly what I am looking for.

    ReplyDelete
  8. neat and clean code..keep up the good work..great post.

    ReplyDelete
  9. Hi, You didn't clarify that add employee in which controller and how to map in the routConfig file

    Thanks.

    ReplyDelete
    Replies
    1. Employee Controller Naturally... You just need to create action methods only for add/edit/delete

      Delete
  10. Very good tutorial, helps to easily get started with NHibernate. Thanks!

    ReplyDelete
  11. Thaks for this tutorial. NHibernate is an alternate for entity framework. So, need some more on NHibernet..

    ReplyDelete
    Replies
    1. You're welcome. Nhibernate is there even before entity framwork!!

      Delete
  12. Nice Tutorial thank's ! but i was wondering how we manage relations between tables.
    wait for ur reply ;)

    ReplyDelete
    Replies
    1. thanks for kind words I will write a separate post for this as soon as I got some time.

      Delete
  13. Thank, was very interesting and also usefully.

    ReplyDelete
  14. Thank was interesting and usefully.

    ReplyDelete
  15. Great post, exactly what I'm looking for. Thank you.

    ReplyDelete
  16. Good 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?

    ReplyDelete
    Replies
    1. can you send me your email address? I will send you code

      Delete
  17. Clear, simple, effective. Many thanks

    ReplyDelete
  18. please my Create code is not working can you pls help me my email Id is gbemigaakindeji@gmail.com

    ReplyDelete
  19. here is my code

    using 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

    ReplyDelete
  20. please give me detail about the relational database one to many mapping through nhibernate as i am new to ORM

    ReplyDelete
  21. Very 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)

    ReplyDelete
  22. Hi 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.

    ReplyDelete
    Replies
    1. check 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

      Delete
  23. Great post, exactly what I'm looking for. Thank you so much :)

    ReplyDelete
  24. Can you provide sample for MVC with ORACLE.

    ReplyDelete
    Replies
    1. Will do that in future blog post. But you can easily find that examples on internet

      Delete
  25. Very nice Code - simple, clear and what i m looking for

    But a annotation:
    NHibertnateSession ... There might be the letter "t" too much ... That's why I first came to stumble

    ReplyDelete
  26. this is my exception please tell me how to solve this:
    An 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();

    ReplyDelete
  27. I'm getting this error, i'm trying to simulate this tuts in vb.net.
    I've explained it well on stackoverflow: http://stackoverflow.com/questions/26489916/nhibernate-vb-net-mvc-could-not-compile-mapping

    ReplyDelete
    Replies
    1. I think you have already got answered it on stackoverflow. This is because of there is namespace problem in your VB.NET Code.

      Delete
  28. I have this error : in list datas

    Linha 41: @foreach (var item in Model)
    Referência de objeto não definida para uma instância de um objeto.


    Whats wrong ?

    ReplyDelete
  29. hi , 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?

    ReplyDelete
    Replies
    1. Not clear what you want to say. Scaffolding still there. Please write your requirement or error clearly.

      Delete
  30. Hi Jalpesh, Thanks for great tutorial but i am getting below error when implementing your code.

    Could not compile the mapping document: C:\MVCSharpArch\MVCSportcalIC\MVCSportcalIC\Models\Nhibernate\Employee.hbm.xml

    Much appreciate if you could help me please

    ReplyDelete
    Replies
    1. There should be some typo in code like suppose in table there a field called name and you have written naem something like this.

      Fore more details go to following link.

      http://stackoverflow.com/questions/16028204/nhibernate-could-not-compile-the-mapping-document

      Delete
    2. Thanks bro it worked it was typo mistake ;)

      Delete
    3. You're welcome glad that you have identified.

      Delete
  31. Great... I was struggling behind this, It really helped me... Thank you so much

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews