Click here to Skip to main content
13,794,318 members
Click here to Skip to main content
Add your own
alternative version


42 bookmarked
Posted 11 Jul 2011
Licenced CPOL

NHibernate Basics

Rate this:
Please Sign up or sign in to vote.
ABCs of NHibernate, a small application to demonstrate save and load of objects to and from Database.
Demo Application UI


NHibernate is an Object-Relational Mapping (ORM) solution for the .NET Platform. It provides a framework for mapping an object oriented domain model to a traditional relational database. It's primary feature is mapping from .NET classes to database tables and from CLR data types to SQL data types.

As the title of this article, we are going to see this feature only; How it loads business object from a database and saves changes from these objects back to the database.


The demo application demonstrates in simple possible way how to setup and use NHibernate. The application creates an Employee object and stores it in a Employee table. It also does some operations like retrieval and deletion of Employee objects, etc. The application is created with NHibernate 3.2.0, VS 2010 and SQL Server 2008.

Using the Code


Here we are going to setup the database first. Use SQL Server Management Studio to create a database that can be used to elaborate with. As shown below, create a new database named NHibernateBasics.

Create New Database

Then add a table called Employee with two columns; ID and Name.

Create New Table

ID shall be the primary key and used as identity. Don’t forget to enable Identity Specification in the properties.

Set Table Properties

Business Object

The database is ready for the demonstration. Now start Visual Studio and create a new WindowsFormsApplication project called NHibernateBasics. Add a new class called Employee.cs with the following code:

namespace NHibernateBasics
    public class Employee
        public virtual int ID { get; set; }

        public virtual string Name { get; set; }

One of NHibernate's strongest features is that it doesn't need special interfaces on business classes. These objects are not aware of the mechanism used to load and save them. However it requires the properties declared as virtual so that it can create proxies as needed.

Mapping XML File

In the absence of specific code for hibernation, someone should guide the translation from the database to business object and back again. This can be achieved through either mapping XML file or by applying attributes on classes and properties. In the demo application, we have used mapping file to keep our business object class clean.

Add a new XML file to the project. The XML file will be used as the mapping file. The name of the file must be Employee.hbm.xml. Both class <name>.cs file and mapping <name>.hbm.xml file should be in same folder and <name> should be same. Add the following content to the file:

 <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 

	namespace="NHibernateBasics" assembly="NHibernateBasics">
  <class name="Employee" table="Employee">
    <id name="ID" column="ID">
      <generator class="identity"/>
    <property name="Name" column="Name"  />

In the properties for the mapping XML file, set build action to Embedded Resource.

Set Mapping File Properties


Add a new application configuration file (app.config). Copy the following content:

 <?xml version="1.0" encoding="utf-8" ?>
    <section name="hibernate-configuration" 

	type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <property name="connection.provider">
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="query.substitutions">hqlFunction=SQLFUNC</property>
      <property name="connection.driver_class">
      <property name="connection.connection_string">
	Data Source=(Local)\SQL2008;Initial Catalog=NHibernateBasics;
	Integrated Security=True</property>
      <property name="show_sql">true</property>
      <mapping assembly="NHibernateBasics" />

Adjust the connection.connection_string property so that it works for your database. Set Catalog=<Database Name>; here it is NHibernateBasics. Set mapping assembly=<Class DLL Name>; here it is again NHibernateBasics.


Now we are almost ready for the demonstration. We just need to access the business class objects and perform certain operations on it.


    // Insert two employees in Database


    // Create the criteria and load data
    ICriteria criteria = mySession.CreateCriteria<employee>();
    IList<employee> list = criteria.List<employee>();
    for (int i = 0; i < myFinalObjects.Length; i++)
        myFinalObjects[i] = list[i];
        MessageBox.Show("ID: " + myFinalObjects[i].ID + " 
			Name: " + myFinalObjects[i].Name);


StringBuilder messageString = new StringBuilder();
// Compare both objects
for (int i = 0; i < 2; i++)
    messageString.AppendLine("Comparing Class Object " + 
	myInitialObjects[i].Name + " and DB Object " + 
	myFinalObjects[i].Name + ". Result = " + 


using (mySession.BeginTransaction())
    // Delete one object from Database


using (mySession.BeginTransaction())
     ICriteria criteria = mySession.CreateCriteria<employee>();
     IList<employee> list = criteria.List<employee>();
     StringBuilder messageString = new StringBuilder();
     // Load and display the data
     foreach (Employee employee in list)
         messageString.AppendLine("ID: " + employee.ID + " Name: " + employee.Name);

NHibernate guarantees that two object references will point to the same object only if the references are set in the same session. If we save the objects in one session and load them in different sessions, then both the objects will be different objects.

Hope it will help you to understand the basics of NHibernate. Happy coding! :)

Points of Interest

Although there are many articles available for NHibernate, target audience for this article are those who just started learning NHibernate, including me :). Another nice article with more information is available here.


  • 07/07/2011 - Initial post


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


About the Author

Kumar, Ravikant INDIA Bangalore
Technical Lead Philips
India India
Have been working with computers since the early 00's. Since then I've been building, fixing, configuring, installing, coding and designing with them. At present I mainly code windows applications in C#, WCF, WPF and SQL. I'm very interested in Design Patterns and try and use these generic principles in all new projects to create truly n-tier architectures. Also I like to code for making the User Interface very attractive...

You may also be interested in...

Comments and Discussions

QuestionVery nice! Pin
dezuzi5-Aug-14 13:03
memberdezuzi5-Aug-14 13:03 
QuestionCodes! Pin
Amir Mohammad Nasrollahi20-Mar-14 9:21
memberAmir Mohammad Nasrollahi20-Mar-14 9:21 
QuestionScope of N-Herbnt: Pin
Member 1000075010-May-13 19:14
memberMember 1000075010-May-13 19:14 
GeneralMy vote of 4 Pin
Himanshu Thawait10-Apr-13 9:07
memberHimanshu Thawait10-Apr-13 9:07 
GeneralMy vote of 5 Pin
srinivasadari24-Mar-13 2:59
membersrinivasadari24-Mar-13 2:59 
BugLooks good, but just does not work ! Pin
manfbraun22-Mar-13 9:43
membermanfbraun22-Mar-13 9:43 
GeneralRe: Looks good, but just does not work ! Pin
Kumar, Ravikant INDIA Bangalore24-Mar-13 21:13
memberKumar, Ravikant INDIA Bangalore24-Mar-13 21:13 
GeneralRe: Looks good, but just does not work ! Pin
manfbraun25-Mar-13 8:38
membermanfbraun25-Mar-13 8:38 
GeneralRe: Looks good, but just does not work ! Pin
Kumar, Ravikant INDIA Bangalore1-Apr-13 23:52
memberKumar, Ravikant INDIA Bangalore1-Apr-13 23:52 
GeneralMy vote of 2 Pin
mosto5514-Mar-13 4:27
membermosto5514-Mar-13 4:27 
GeneralRe: My vote of 2 Pin
Kumar, Ravikant INDIA Bangalore14-Mar-13 6:59
memberKumar, Ravikant INDIA Bangalore14-Mar-13 6:59 
QuestionIdentity column get Pin
Vishal_00710-Jan-13 0:27
memberVishal_00710-Jan-13 0:27 
AnswerRe: Identity column get Pin
Kumar, Ravikant INDIA Bangalore18-Jan-13 0:36
memberKumar, Ravikant INDIA Bangalore18-Jan-13 0:36 
GeneralRe: Identity column get Pin
Vishal_0071-Feb-13 4:56
memberVishal_0071-Feb-13 4:56 
QuestionExcellent Pin
havitia22-Aug-12 12:23
memberhavitia22-Aug-12 12:23 
AnswerRe: Excellent Pin
Kumar, Ravikant INDIA Bangalore22-Aug-12 20:36
memberKumar, Ravikant INDIA Bangalore22-Aug-12 20:36 
Questionthank you verry much Pin
smaily0076-Feb-12 12:26
membersmaily0076-Feb-12 12:26 
AnswerRe: thank you verry much Pin
Kumar, Ravikant INDIA Bangalore29-Jul-12 20:29
memberKumar, Ravikant INDIA Bangalore29-Jul-12 20:29 
QuestionNice code Pin
vimalprakash31-Jan-12 20:53
membervimalprakash31-Jan-12 20:53 
AnswerRe: Nice code Pin
Kumar, Ravikant INDIA Bangalore29-Jul-12 20:28
memberKumar, Ravikant INDIA Bangalore29-Jul-12 20:28 
GeneralWhat a great article Pin
feelyd27-Jan-12 5:42
memberfeelyd27-Jan-12 5:42 
GeneralRe: What a great article Pin
Kumar, Ravikant INDIA Bangalore29-Jul-12 20:28
memberKumar, Ravikant INDIA Bangalore29-Jul-12 20:28 
GeneralMy vote of 5 Pin
Member 250201316-Jul-11 4:52
memberMember 250201316-Jul-11 4:52 
QuestionRollback() not seen in your code Pin
digimanus11-Jul-11 23:56
memberdigimanus11-Jul-11 23:56 
AnswerRe: Rollback() not seen in your code Pin
Kumar, Ravikant INDIA Bangalore12-Jul-11 18:29
memberKumar, Ravikant INDIA Bangalore12-Jul-11 18:29 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.181207.3 | Last Updated 11 Jul 2011
Article Copyright 2011 by Kumar, Ravikant INDIA Bangalore
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid