Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Select & Insert Operation

NHibernate is a open source Object-Relational Mapping (ORM) tool. This ORM tool hides sql query complexities by replacing query with mapping and class object.
Every .Net Project can use Nhibernate to work with database.

The purpose of NHibernate is to save developers work time thus increasing productivity. Large application may get more benefit from NHibernate than small app.

This blog post gives Asp.Net & NHibernate dummy examples. These examples cover select / retrieve records and insert a new record.

First thing first, we need to download Nhibernate files. Please download the zip file from http://sourceforge.net/projects/nhibernate/

As a brief, we need xml mapping file, a class which representates DB table, Nhibernate dll file, NHibernate xml configuration file, and Asp.Net file it self that contains NHibernate configuration object, NHibernate session etc to provide data to UI.

I use VS 2010 Express & SQL Server 2008 R2 to build this example.

Create a DB Table & Class library file

  1. Create ‘tb_person’ table with below script:
    CREATE TABLE [dbo].[tb_person](
    	[Name] [nvarchar](50) NULL,
    	[City] [nvarchar](50) NULL,
    	[Province] [nchar](10) NULL,
    	[ID] [int] IDENTITY(1,1) NOT NULL,
     CONSTRAINT [PK_tb_person] PRIMARY KEY CLUSTERED 
    (
    	[ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    

    Basically the tb_person has ID as primary key and Name, city, and province as columns.

  2. Create new Class Library Project and save it as ‘PersonLibrary’
  3. Add new Class file and save it as ‘Person.cs’. This class is used as object representative of ‘tb_person’ table.
    Its source code below:

    namespace PersonLibrary
    {
        public class Person
        {
            private int _PersonID;
            private string _name;
            private string _city;
            private string _province;
    
            public virtual int PersonID
            {
                set { _PersonID = value; }
                get { return _PersonID; }
            }
    
            public virtual string Name
            {
                set { _name = value; }
                get { return _name; }
            }
    
            public virtual string City
            {
                set { _city = value; }
                get { return _city; }
            }
    
            public virtual string Province
            {
                set { _province = value; }
                get { return _province; }
            }
    
            public Person()
            {
            }
        }
    }
    

    Remember that we must put ‘virtual’ keyword on each Class Property to work with NHibernate. Each property uses set and get keyword like saving & getting a field value.

  4. Add new xml file and save it as ‘Person.hbm.xml’. This xml file is a mapping file that relates ‘Person’ class with ‘tb_person’ table.
    The naming convention is ‘<Class_Name>.hbm.xml’. Replace <Class_Name> with the related class name which in this case is ‘Person’.

    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                       namespace="PersonLibrary"
                       assembly="PersonLibrary">
      <class name="Person" table="tb_person">
        <id name="PersonID" column="ID" type="Int32" unsaved-value="0">
          <generator class="native"></generator>
        </id>
        <property name="Name"  column="Name" type="String"/>
        <property name="City"   column="City"  type="String"/>
        <property name="Province"      column="Province"      type="String"/>
        
      </class>
    </hibernate-mapping>
    

    This xml file’s content is more or less self explanatory. Namespace & assembly is set to Project Namespace & Name which has same name, PersonLibrary.
    There is class tag with name attribute value setted to class name that we had and also table value filled in with ‘tb_person’.
    Inside class tag, there is id tag along with related column, type, unsaved-value attribute value. Unsaved-value means that if the ID is ‘0’ then operation will be insert.
    Since ID is primary key so we have generator tag with ‘native’ mode.
    The rest are property with name, column, and type attribute value accordingly.

    Set this xml file’s Build Action Property to Embedded Resource in VS.

  5. Build this class library project

Try to insert some records into ‘tb_person’ table for testing purposes.

Website Project Using NHibernate

  1. Create a new website project and save it as ‘PersonWebNHB’ or else.
  2. Add new reference and point it to PersonLibrary.dll. This library has been built in previous step.
  3. Add new reference again and point it to NHibernate.dll. This library is located at downloaded file, NHibernate-3.3.2.GA-bin.zip.
    Under Required_bins folder.
  4. Add new xml file, hibernate.cfg.xml. This xml file is a NHibernate config file which has DB Connection 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="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    
            <property name="connection.connection_string">
                Data Source=(local)\SQLDEV;Initial Catalog=TestDB;user id=sa;password=pwd;
            </property>
        </session-factory>
    </hibernate-configuration>
    

    The property value can be found at downloaded file, NHibernate-3.3.2.GA-bin.zip, under Configuration_Templates. Since I use SQL Server 2008 then I look at MSSQL.cfg.xml
    At last, the used config file must have name ‘hibernate.cfg.xml’. However, this hibernate.cfg.xml file’s property Copy to output directory value must set to Copy Always.

  5. Create a new webform file (Default.aspx). This file will retrieve all data in ‘tb_person’ and list them in Literal control.
    <form id="form1" runat="server">
        <div>
            <asp:Literal ID="Literal1" runat="server"></asp:Literal>
            <br />
            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/WebForm1.aspx">Insert New Data</asp:HyperLink>
        </div>
        </form>
    

    There is a hyperlink control to add a new record.

  6. Default.aspx code behind file:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using NHibernate;
    using NHibernate.Cfg;
    using PersonLibrary;
    using System.Text;
    
    namespace PersonWebNHB
    {
        public partial class Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                PopulatePerson();
            }
    
            protected void PopulatePerson()
            {
                Configuration config = new Configuration();
                config.Configure();
    
                config.AddAssembly("PersonLibrary");
                ISessionFactory factory = config.BuildSessionFactory();
                ISession session = factory.OpenSession();
                IList<Person> persList = session.QueryOver<Person>().List<Person>();
               
                session.Close();
    
                StringBuilder sb = new StringBuilder();
                foreach (Person pers in persList)
                {
                    sb.Append(pers.PersonID + " " + pers.Name + " " + pers.City + " " + pers.Province + "<br>");
                }
                Literal1.Text = sb.ToString();
            }
        }
    }
    

    We have Common lines when we work with Nhibernate which are Configuration, AddAssembly, BuildSessionFactory, and OpenSession.
    After that use QueryOver() object to retrieve record(s). This QueryOver uses LinQ like syntax. In this case no filter/’where’ condition. So all records will be retrieved.
    Also it uses List() method to convert into IList object. The IList object is iterated and its member is accessed like we access a class member.

  7. Run it and see result
  8. Create a new WebForm file (WebForm1.aspx) to insert new record to ‘tb_person’.
      <form id="form1" runat="server">
        <div>
        
        <asp:Label ID="lblname" runat="server" Text="Name:"></asp:Label><asp:TextBox ID="txtname" runat="server"></asp:TextBox><br />
            <asp:Label ID="lblLastName" runat="server" Text="City:"></asp:Label><asp:TextBox ID="txtcity" runat="server"></asp:TextBox><br />
            <asp:Label ID="lblEmail" runat="server" Text="Province:"></asp:Label><asp:TextBox ID="txtprovince" runat="server"></asp:TextBox><br />
            
            <asp:Button ID="btnSavePerson" runat="server" Text="Save Person" 
                onclick="btnSavePerson_Click" />
        </div>
        </form>
    
  9. Code behind file, Webform1.aspx.cs. This code use Person class, fill in its property values and pass this class object to Nhibernate session to save into table.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using PersonLibrary;
    using NHibernate;
    using NHibernate.Cfg;
    
    namespace PersonWebNHB
    {
        public partial class WebForm1 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void btnSavePerson_Click(object sender, EventArgs e)
            {
                // setup nhibernate configuration
                Configuration config = new Configuration();
                config.Configure();
                // add our assembly
                config.AddAssembly("PersonLibrary");
                // setup nhibernate session
                ISessionFactory factory = config.BuildSessionFactory();
                ISession session = factory.OpenSession();
                // start nhibernate transaction
                ITransaction transaction = session.BeginTransaction();
    
                Person pers = new Person();
                pers.Name = txtname.Text;
                pers.City = txtcity.Text;
                pers.Province = txtprovince.Text;
    
                session.SaveOrUpdate(pers);
                transaction.Commit();
                session.Close();
    
                Response.Redirect("Default.aspx");
            }
        }
    }
    

    Same as above method, there are common lines which are Configuration, AddAssembly, BuildSessionFactory, and OpenSession.
    The difference with this ‘Insert’ operation are using BeginTransaction, SaveOrUpdate, and Commit. SaveOrUpdate means if the table ID (primary key) which is PersonID is not set or 0 then it is insert operation otherwise it is update.

  10. Run it

Cheers,
Agung Gugiaji

Advertisements

2 responses to “Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Select & Insert Operation

  1. Pingback: Asp.Net & ORM Tool NHibernate For Dummy Tutorial – Update & Delete Operation | Enlighten Application Developer Journals

  2. Beautiful explanation
    Thank you so much for such a nice article

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s