DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • Implementing the Repository Pattern Using C# and Entity Developer in ASP.NET Core
  • How to View MongoDB Collections as Diagrams
  • The Complete Tutorial on the Top 5 Ways to Query your Relational Database in JavaScript - Part 1

Trending

  • Accelerating AI Inference With TensorRT
  • Mastering Advanced Aggregations in Spark SQL
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  1. DZone
  2. Data Engineering
  3. Databases
  4. Getting Started with NHibernate and ASP.NET MVC- CRUD Operations

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

By 
Jalpesh Vadgama user avatar
Jalpesh Vadgama
·
Oct. 01, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
46.9K Views

Join the DZone community and get the full member experience.

Join For Free

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.

ASP.NET MVC ASP.NET Database connection NHibernate Relational database

Published at DZone with permission of Jalpesh Vadgama, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • Implementing the Repository Pattern Using C# and Entity Developer in ASP.NET Core
  • How to View MongoDB Collections as Diagrams
  • The Complete Tutorial on the Top 5 Ways to Query your Relational Database in JavaScript - Part 1

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: