Wednesday, March 9, 2011

Starting with NHibernet

Reading some useful document finally I can run a one page project using nhibernet. The project is simple as it can only add a record in a database table. But as a beginner with nhibernet I have faced some problem to run the project. In this article I will try to demonstrate the step to work with nhibernet for a beginner. I will show the necessary step to configure the project for working with nhibernet for a begginer.

First step First:  At first I need the Nhibernet. So let’s download it from Download NHibernet. After downloading we will do the following task. 
  1.  Install Nhibernet
  2. Create a simple business object class  
  3. Create a Nhibernet mapping to load and save the business object 
  4.  Configure the Nhibernet
  5. Write a save method to save the data in database
After do the entire step my solution explorer looks like

                                                        Figure: Solution Explorer
Install Nhibernet: Create a folder and name it Nhibernet unzip the downloaded Nhibernet zip file in that nhibernet folder. You will see some folder and file. Add the Nhibernet.dll reference to your project which is in Required_Bins(after unzip Nhibernet this folder will create) folder. That’s all to install Nhibernet.

Create a Simple Business Object Class: Actually in this article we just follow the step to working with Nhibernet. We do not discuss detail about Nhibernet. In this step we will create a simple business object class which is used to save the data in database. In my case I have a table in my test database named ‘t_Department’. So I create a object class for this table. The following figure shows the object explorer of the database.


The following figure shows the business object class layout.

Create a NHibernet mapping to load and save the business object: Create a folder 'Mappings' in our NHibernetApp project. Add an xml file and name it 'Department.hbm'. Define Embedded Resource for Build Action for the xml file. Now we add 'nhibernate-mapping.xsd' file in our Department.hbm xml file's Schemas properties so that VS provide us intellisense and validation when we edit xml mapping document. To add the 'nhibernate-mapping.xsd' file follow the following step.
  1. Create a folder name 'SharedLibs' in NHibernetApp project directory using windows explorer.
  2. Copy the 'hibernate-mapping.xsd' file from extracted NHibernet's 'Required_Bins' folder and copy it to 'SharedLibs' folder.
  3. From VS open the  Department.hbm file. Right click and go to properties.
  4. Map the hibernate-mapping.xsd file to Schemas properties.
The following figure shows the Properties window.
Now add the following line in Department.hbm xml file.

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernetApp"   namespace="NHibernetApp.Domian">
  <class name="NHibernetApp.Domian.Department" table="t_Department">

    <id name="OID" column="OID" type="String" unsaved-value="0">
      <generator class="assigned" />

    <property name="departmentName" column="department_departmentName" 
              type="String" />
    <property name="facaltyName" column="department_facaltyName" type="String" />

The mapping file looks like the following figure

Look at the class tag's name property. Always use a fully qualified name of the class for name property.

Configure NHibernet: In this step we will see how to configure NHibernet. In my case i use SQL Server 2008. The following step should be followed
  1. Add a xml file to the root of the project (my case it is NHibernetApp).
  2. Named the xml file 'hibernate.cfg.xml'
  3. Set it's 'Copy to Output Directory' to 'Copy always'
  4. Add the following line to the xml file

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.connection_string">
Data Source=REGOR;Database=MVCTest;Uid=sa;Pwd=sa
    <property name="connection.provider">
    <property name="dialect">
    <property name="connection.driver_class">
    <property name="proxyfactory.factory_class">
    <property name="show_sql">true</property>

Please change the connection_string property as your machine. Finally add two more ddl 'NHibernate.ByteCode.LinFu.dll' and 'LinFu.DynamicProxy.dll' in your project references. The ddl's are located in extracted NHibernet folders 'Required_For_LazyLoading\LinFu' folder. That's all, the configuration is complete.

Finally: Finally we will add two more class to save data in database. Just follow the following step
  1. Add a new folder in the project (My case Manager).
  2. Add an interface to the newly added folder (My case DBMgr.cs) .
  3. Add a class file to the added folder (My case RegMgr.cs).
  4. Add the following code to the DBMgr.cs interface

namespace NHibernetApp.Manager
    public interface DBMgr
        //IList getDepartments();
        //Department getDepartment(int id);
        void saveDepartment(Department dept);

        //IList getClasses();

Now just implement the DBMgr interface in RegMgr.cs class. The source code of the class would be.

public class RegMgr:DBMgr

    Configuration config;
    ISessionFactory factory;

    public RegMgr()
       config = new Configuration();
       factory = config.BuildSessionFactory();

    public void saveDepartment(NHibernetApp.Domian.Department dept)

        ISession session = null;
        ITransaction tx = null;
           session = factory.OpenSession();
           tx = session.BeginTransaction();
           if (dept.OID == null)
              dept.OID = "1234";
        catch (Exception ex)


That's all friends. If you want you can download my code from this link. Click Here

Conclusion: I think this article will help the begging for starting with NHibernet first time. I again replay that it is a simple article for begging. If you want to be a specialist on NhHibernet there is no alternative to read books and do more exercise.

1 comment:

  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..

    c#,, php tutorial

    Thanks a lot..!