Wisdom of Helios

Tutorial on NHibernate and FluentNhibernate

11 Comments

This tutorial will be well-understood with a project , that can be downloaded  from  here

DownLoad FullCode.

NHibernate in a Nutshell :
NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform,it provides an easy way to use framework for mapping an object-oriented domain model to a traditional relational database. NHibernate is a .NET based object persistence library which helps to persist our .NET objects to and from an underlying relational database. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

“If we use an RDBMS to store our data (or state) then the data is stored in tables. Thus we have to map our object model to corresponding tables in the database. This mapping doesn’t necessarily have to be one to one (and most often it is not). That is we do not always have mapping where one object maps to one table. Very often the content of one table maps to different object.”

FluentNHibernate in a Nutshell :
To be formal – “Fluent NHibernate provides a way for you no longer need to write the standard NHibernate mapping file (. Hbm.xml), but you can use the C # mapping file to write. Doing so, facilitate the reconstruction of our code to provide the code readability, and streamlining the project code.”
The greatest advantage of FluentNHibernate is – the mapping is type-safe since it is not based on strings.

In the past the mapping between the object model and the underlying database has been mainly done by defining XML documents.

Fluent NHibernate canceled the xml file.
Why  needs to replace the XML file?
a. XML is not real-time compiled. When your XML configuration file has errors, you can see only in the run-time what went wrong.
b. XML is very cumbersome. Indeed, in the NHibernate configuration file, xml node is very simple, but still can not cover up the cumbersome nature of XML file itself.
c. Repeat mapping file attributes set. For example, in xml, we need to set for each string type fields are not allowed to be empty, the length is greater than 1000, int type had to have a default value is -1, the end of the xml configuration file so you will find a lot of repetition work.

one can define the mappings in C# which is a full blown programming language and not only a data description language as XML is. This fact opens the door for many – previously unthinkable – possibilities since the mapping can now contain logic.

Step By Step Approach:

Now we will build a very simple web application  which will store, update, read and delete Car data using NHibernate and FluentNhibernate.
Step 1:
From the VS editor we will create a new web application. We will add reference of NHibernate and FluentNhibernate from here……
Step 2:
We will create a new class file by giving a name “Tables.cs”. In this class file we will add all the classes that we planned to map to the Database. At first we will create a very simple class named “Car” with properties (all class should contain property)

public class Core
{
public virtual int Id { get; set; }

}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}

Step 3:
Ok, so now we have to tell NHibernate how to map our entities to the database. We’re going to use the FluentNHibernate interface to do this, so all configuration is in code. We will create another class such as CarMap that inherits ClassMap<Car>. This is what lets FluentNHibernate know to use these mappings with the Car class we’ve just defined. If we look at the configuration,  it’s saying what’s the Id field. Handily called Id in this example. NHibernate has the ability to generate auto Ids and there are many options which are beyond our scope here. Lets have look to the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{

       public CarMap()

       {

           LazyLoad();

           Id(x => x.Id);

           Map(x => x.Title).Not.Nullable().Length(100);

           Map(x => x.Description);

           Table(“Car”);

       }

    }
}

With this statement we define the mapping of the property Title which is mandatory and thus cannot be null. We also tell the system that its maximal length is 100 characters. If we do not explicitly define the name of the column in the corresponding table on the database will be the same as the name of the mapped property. In our case this is Title. Of course this can be changed anytime by using the appropriate syntax.
You might wonder what the LazyLoad() means. A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only when it is used. I recommend you to read this Article1 & Article2  to know more about lazy loading.
LazyLoad() is an optional field.

Step 4:
Now the challenge appears- we need to tell NHibernate how to connect to the database.
At First We have to choose the Database. Here I have used SQLEXPRESS 2008 which is provided with VS 2010. Here I have created a database named ”nhub”. We will access this database through Server Explorer of the VS Editor.

Here is the place where we will apply our business logic and reduce the number and necessity of writing cumbersome stored procedures.

When we impose CRUD on RDBMS through NHibernate, all the operations is held by the NHibernate Session (Nhibernate session is different from ASP.NET session and they are totally different).  It may be easier to think of a session as a cache or collection of loaded objects relating to a single unit of work. NHibernate can detect changes to the objects in this unit of work..To handle these sessions we will use some interfaces that comes form NHibernate.These interfaces are the main point of dependency of application business/control logic on NHibernate.

Five basic Interfaces used as shown in the figure below; where IQuery and ICriteria performs the same operation.

ISession interface
1.  The ISession interface is the primary interface used by NHibernate applications, it exposes NHibernates methods for finding, saving, updating and deleting objects.

2.  An instance of ISession is lightweight and is inexpensive to create and destroy. This is important because your application will need to create and destroy sessions all the time, perhaps on every ASP.NET page request. NHibernate sessions are not thread safe and should by design be used by only one thread at a time. The NHibernate notion of a session is something between connection and transaction.

3.  We sometimes call the ISession a persistence manager because it’s also the interface for persistence-related operations such as storing and retrieving objects. Note that a NHibernate session has nothing to do with an ASP.NET session.

ISessionFactory interface
1.  The application obtains ISession instances from an ISessionFactory. Compared to the  ISession interface, this object is much less exciting.

2.  The ISessionFactory is certainly not lightweight! It’s intended to be shared among many application threads. There is typically a single instance of ISessionFactory for the whole application-created during application initialization, for example. However, if your application accesses multiple databases using NHibernate, you’ll need a SessionFactory for each database.

3.  The SessionFactory caches generated SQL statements and other mapping metadata that NHibernate uses at runtime.

4.  It can also hold cached data that has been read in one unit of work, and which may be reused in a future unit of work or session. This is possible if you configure class and collection mappings to use the second-level cache.

ITranscation interface
1.  The ITransaction interface, next to the ISession interface. The ITransaction interface is an optional API. NHibernate applications may choose not to use this interface, instead managing transactions in their own infrastructure code.

2.  A NHibernate ITransaction abstracts application code from the underlying transaction implementation-which might be an ADO.NET transaction or any kind of manual transaction-allowing the application to control transaction boundaries via a consistent API. This helps to keep NHibernate applications portable between different kinds of execution environments and containers.

IQuery and ICriteria interfaces
1.  The IQuery interface gives you powerful ways of performing queries against the database, whilst also controlling how the query is executed.

2.  It is the basic interface used for fetching data using NHibernate. Queries are written in HQL or in the native SQL dialect of your database. An IQuery instance is lightweight and can’t be used outside the ISession that created it. It is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

3.  The ICriteria interface is very similar; it allows you to create and execute object-oriented criteria queries.

Now, I will discuss some points from my written code for configuring the FluentNibernate . We have create a class called ModelClass:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace ModelClass
{
public class NHibernateHelper
{

       private static ISessionFactory _sessionFactory;

       private static ISessionFactory SessionFactory

       {

           get

           {

               if (_sessionFactory == null)

                   InitializeSessionFactory();

               return _sessionFactory;

           }

       }

       private static void InitializeSessionFactory()

       {

           _sessionFactory = Fluently.Configure()

               .Database(MsSqlConfiguration.MsSql2008

                             .ConnectionString(

                                 @”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)

               .Mappings(m =>

                         m.FluentMappings

                             .AddFromAssemblyOf<Car>())

               .ExposeConfiguration(cfg => new SchemaExport(cfg)

                                               .Create(true, true))

               .BuildSessionFactory();

       }

public static ISession OpenSession()

       {

               return SessionFactory.OpenSession();

       }

    }
}

There’s quite a bit going on here. .Database(MsSqlConfiguration.MsSql2008 is where we tell NHibernate to use the SQL Server driver, there are numerous others, including MySql and SQLLite which are the popular one’s I’m aware of. The .ConnectionString is obvious we’re connecting to the database we defined above.

The next bit is optional .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true)) tells NHibernate to actually create the tables in the database if they’re not there. We don’t really want to leave this on otherwise eachtime we run our app it’ll drop the tables with all our Cars in them and recreate them. the Create(true,true) also refers to whether to show the SQL generated to drop the tables, which we’ve turned on so we can see it work its magic.

Finally we BuildSessionFactory() which will  build the session factory and we assign it to a static variable so as to only use one Session for the lifetime of our application

Step 5:
All configuration is completed so far, now we will create a very simple webpage that prompt a user to create a table name “Car” for the first time if the table does not exist and then insert data into “Car” table.
We create a page just like below

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Add Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:TextBox ID=”txtTitle” runat=”server”></asp:TextBox>
</td>

<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
<asp:Label ID=”lblsatat” runat=”server” Text=”” ForeColor=”#FF5050″></asp:Label>
</asp:Content>

Step 6:
Now in the “ModelClass.cs” we will add this piece of code to add Car to the “Car” table.
public static void Add<T>(T entity)
{

           using (ISession session = OpenSession())

           using (ITransaction transaction = session.BeginTransaction())

           {

               session.Save(entity);

               transaction.Commit();

               session.Flush();

               session.Close();

           }

}

We will add an event  in the Page Class which will fire when the Save button is clicked

protected void btnSave_Click(object sender, EventArgs e)

       {

                Create(txtTitle.Text.ToString(), txtDesc.Text.ToString());

}

}

Notice we’re using the Session we just new up a Car class simply give it a name and then session.Save(entity) but note that it doesn’t actually get added to the database until you Commit the Transaction.
There’s a simple order here:

  1. Open Session
  2. Begin Transaction
  3. Do Something
  4. Commit the Transaction
  5. Close the transaction
  6. Close the Session

Now because we have a using statement we’re automatically calling Dispose on the Transaction and the session. The session.save(entity) figures out the appropriate SQL to generate for us.

Step 7:
This time we will recreate the “Car” class and create another class “Manufacturer”. We will assume that A Car has a Manufacturer and it is a One to Many relation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
namespace NHibernateTutorial
{

public class Core
{
public virtual int Id { get; set; }

}
public class Car : Core
{

       public virtual string Title { get; set; }

       public virtual string Description { get; set; }

       public virtual Manufaturer ManuFacturedBy { get; set; }

    }
public class Manufaturer : Core
{
public virtual string Name { get; set; }
}
}
Step 9:
We have to Map the classes again like below –

using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{

       public CarMap()

       {

           Id(x => x.Id);

           Map(x => x.Title).Not.Nullable().Length(100);

           Map(x => x.Description);

           References(x => x.ManuFacturedBy).Column(“ManufacturerID”).Not.LazyLoad();

           Table(“Car”);

       }

    }

public class ManufaturerMap : ClassMap<Manufaturer>
{

       public ManufaturerMap()

       {

           Id(x => x.Id);

           Map(x => x.Name);

           Table(“Manufacturer”);

       }

}
}

Step 10:
We will write the following code to save data now-

public void Create(string carTitle, string carDesc)
{
Car cr = new Car();
cr.Title = carTitle;
cr.Description = carDesc;
cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() };
ModelCode.Add<Manufaturer>(cr.ManuFacturedBy);

ModelCode.Add<Car>(cr);

       }
Here, “cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() }” is initaing the “Car” object with “Manufacturer” object. While saving data we have to save the manufacturere object first then Car object.

Step 11:
Now we will retrieve data from the database. to show the data we first add a GridView named “gdvShowCar” to a newly created Webform “ShowCar.aspx”.

Now we will add a method named “Get” in out ModelCode class.

public static IList<T> Get<T>()
{

           IList<T> centers;

           using (ISession session = OpenSession())

           {

               centers = session.CreateCriteria(typeof(T))

                   .List<T>();

           }

           return centers;

       }

This method will return a list to us. the CreateCriteria() take a class  which will be queried as a parameter and return an ICriteria Object.
Now in “ShowCar.aspx.cs” we will write –

public partial class ShowCar : System.Web.UI.Page
{

       protected void Page_Load(object sender, EventArgs e)

       {

               LoadData();

       }

       public void LoadData()

       {

           IList<Car> Icar = ModelCode.Get<Car>();

           var cars = from car in Icar select new { car.Title, car.Description };

           gdvShowCar.DataSource = cars;

           gdvShowCar.DataBind();

       }

    }

This code will fill the griedview with data.

Step 12:
Now we will update data . we will first create a page named ”UpdateCar”. there we will create a drop down list of Car’s name. We will select a name from the list and update data according to this particular Car name.

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Site.Master” AutoEventWireup=”true” CodeBehind=”UpdateCar.aspx.cs” Inherits=”NHibernateTutorial.UpdateCar” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”server”>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Update Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:DropDownList ID=”ddlCarTitle” runat=”server” AutoPostBack=”True”></asp:DropDownList>
</td>

<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Manufacturer Name:
</td>
<td>
<asp:TextBox ID=”txtMan” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
</asp:Content>

we did not bind data to the dropdownlist yet. To do that we will simply call the “Get” method fromModelCode class.
we can write –

protected void Page_Load(object sender, EventArgs e)

       {

           if (!IsPostBack)

           {

               initData();

           }

       }
public void initData()
{

           IList<Car> cars = ModelCode.Get<Car>();

           ddlCarTitle.DataSource = cars.ToList();

           ddlCarTitle.DataTextField = “Title”;

           ddlCarTitle.DataValueField = “Id”;

           ddlCarTitle.DataBind();

       }

The DropDownList is filled with data now. Next, we have to Load our text boxes with appropriate data. For this we will create an overloaded method of “Get” inside the “DataModel” class. this method may looks like below –

public static IList<T> Get<T>(string property, object value)
{
IList<T> centers;
using (ISession session = OpenEngineSession())
{
centers = session.CreateCriteria(typeof(T))
.Add(Restrictions.Eq(property, Convert.ToInt32(value)))
.List<T>();
}
return centers;
}
the eq() searches a match for the (property,value) pair and return a List. It works like traditional WHERE clause with a SELECT statement.

Now we will create an method in the page class named “LoadCarInfo” this method will load data on form when the DropDownList of  Name is being populated.

public void LoadCarInfo()
{

var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString());

           if (inv.Count > 0)

           {

               txtDesc.Text = inv[0].Description;

               txtMan.Text = inv[0].ManuFacturedBy.Name;

           }

       }

Now , time to UpDate data. This very similar to “Add” in the ModelCode class.
We will add another method to “ModelCode”. It is very easy and understandable.
public static void Update<T>(T entity)
{

           using (ISession session = OpenSession())

           using (ITransaction transaction = session.BeginTransaction())

           {

               session.Update(entity);

               transaction.Commit();

               session.Flush();

               session.Close();

           }

       }
So now we can call this “Update” from our Page Class as before-

protected void btnSave_Click(object sender, EventArgs e)
{

var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString())[0];

           inv.Description = txtDesc.Text;

           inv.ManuFacturedBy.Name = txtMan.Text;

           ModelCode.Update<Manufaturer>(inv.ManuFacturedBy);

           ModelCode.Update<Car>(inv);

       }

Step 13:
Now we will Delete data. We will add another method in “ModelCode”.

public static void Remove<T>(T entity)
{
using (ISession session = OpenEngineSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}

Conclusion:
Here I have tried to given some basic CRUD operation using NHibernate and FluentNHibernate. Many thing is left and overlooked intentionally because the limitation of my scope. Actually It takes time to be expert and skilled with these technology.

DownLoad FullCode.

Author: Munir

I'm good for nothing

11 thoughts on “Tutorial on NHibernate and FluentNhibernate

  1. Very nice article clearly shown every aspect
    Thanks

  2. Hi,

    I will develop an asp.net web project with FluentNHibernate. I created
    my project. I’m always taking errors about with connection string. I
    investigated a lot about this topic. But, i couldnt find a solution.

    Error:
    An invalid or incomplete configuration was used while creating a
    SessionFactory. Check PotentialReasons collection, and InnerException
    for more detail.

    Are there anybody solve this problem?
    The function that it will create my database where is in NHibernate
    Helper class.

    private static void InitializeSessionFactory()
    {
    _sessionFactory = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008
    .ConnectionString(

    @”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)
    )
    .Mappings(m =>
    m.FluentMappings
    .AddFromAssemblyOf())
    .ExposeConfiguration(cfg => new SchemaExport(cfg)
    //.Create(true, true)
    )
    .BuildSessionFactory();
    }

    I’m waiting for your help…

    • Hi Semih Kırdinli, sorry for my late response. Recently I’m working on IP Mulmedia Subsystem based Application and away from NHibernate and my blog. I think you did not able to create the Database, right? OK, simply uncomment the code snippet –

      private static void InitializeSessionFactory()
      {
      _sessionFactory = Fluently.Configure()
      .Database(MsSqlConfiguration.MsSql2008
      .ConnectionString(
      
      @”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)
      )
      .Mappings(m =>
      m.FluentMappings
      .AddFromAssemblyOf())
      .ExposeConfiguration(cfg => new SchemaExport(cfg)
      .Create(true, true)                // Uncomment here.
      )
      .BuildSessionFactory();
      }
      

      So you will be able to map your classes into DB table.

  3. My database is Ms Sql Server 2008. I want to extract my db from by code. Only my server name different froum yours. But, the code had an error, when i changed my connection string or server name.What can i repair this.

  4. I can’t download your link. Please post your link again.

  5. Thanks a lot your post was very useful.Please write more tutorials like these.

  6. can’t download your link 😥

  7. Hi, when follow all instruction and configuration , my project successfully run but every time this

    Car cr = new Car();
    cr.Title = carTitle;
    cr.Description = carDesc;
    cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() };
    ModelCode.Add(cr.ManuFacturedBy);
    ModelCode.Add(cr);

    the above code creates new manufatture object .

    I want reference of Manufacture in Car …….

Leave a comment