In this article I will explain with an example, how to use NHibernate library to select records from database in ASP.Net using C# and VB.Net.
 
 

What is NHibernate?

NHibernate is an open source object-relational mapper for the .NET framework.
The primary feature is mapping from .NET classes to database tables.
It is based on Hibernate which is a popular Java object-relational mapper and it has a very mature and active code base.
It provides a framework for mapping an object-oriented model to a traditional relational database.
It's built on top of ADO.Net.
NHibernate supports a wide variety of different databases like SQL Server, Oracle, MySQL, PostgreSQL and etc.
 
 

Steps for implementing NHibernate

Following are the steps for implementing NHibernate in ASP.Net.
1. Install the NHibernate package from Nuget.
2. Create a class and define the properties.
3. Create a NHibernate mapping to load and save the business object.
4. Configure NHibernate to talk to the database.
 
 

Downloading NHibernate package

You will need to install the NHibernate package from Nuget.
 
 

Database

I have made use of the following tables Customers with the schema as follow.
Using NHibernate in ASP.Net using C# and VB.Net
 
I have already inserted few records in the table.
Using NHibernate in ASP.Net using C# and VB.Net
 
Note: You can download the database table SQL by clicking the download link below.
           Download SQL file
 
 

Property Class

The class consists of following properties.
The class will contain properties with names similar to the Customers Table. This is necessary as it will be used to load the appropriate fields in appropriate properties i.e. CustomerId will be loaded in CustomerId property.
Note: The properties needs to be assign with the key word virtual in C# and Overridable in VB.Net. Because NHibernate is by default configured to use lazy load for all entities.
 
public class Customer
 {
     public virtual int CustomerId { getset; }
     public virtual string Name { getset; }
     public virtual string Country { getset; }
 }
 
VB.Net
Public Class Customer
    Public Overridable Property CustomerId As Integer
    Public Overridable Property Name As String
    Public Overridable Property Country As String
End Class
 
 

Defining the Mapping

In order to enable mapping, you will need to add a new xml document by right clicking on the Solution Explorer and click on Add and then New Item.
Form the Add New Item dialog window, select XML File and give a suitable name i.e. Customer.hbm.xml and click on Add.
This is used by NHibernate to automatically recognize the file as a mapping file.
Note: The hbm is a part of the file name.
 
Using NHibernate in ASP.Net using C# and VB.Net
 
Once the xml file has been added, you need to set the Build Action with Embedded Resource.
For that, right click on the xml file and select Properties.
Using NHibernate in ASP.Net using C# and VB.Net
 
In the Properties dialog window, change the Build Action from Content to Embedded Resource as shown below.
Using NHibernate in ASP.Net using C# and VB.Net
 
Using NHibernate in ASP.Net using C# and VB.Net
 
Inside the xml file you need to add hibernate-mapping root node to define mapping file.
Note: You need to define two attributes assembly and namespace of the root node.
 
Inside the hibernate-mapping node, define the class node and specify the following attributes.
name – Name of the class.
table – Name of the database table.
Inside the class node, define the property column according to the property as shown below.
Note: For more details on mapping declaration, please refer the documentation here.
 
<?xml version="1.0" encoding="utf-8" ?> 
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2
                   assembly="NHibernate_ASPNet
                   namespace="NHibernate_ASPNet"
    <class name="Customertable="Customers
        <id name="CustomerId" column="CustomerId"
            <generator class="identity" /> 
        </id>
        <property name="Name" /> 
        <property name="Country/> 
    </class>
</hibernate-mapping>
 
Now inside the Web.Config, you need to define the settings for connecting using data provider using hibernate-configuration.
The data provider has the following properties:
connection.provider – The type of a custom IConnectionProvider implementation.
dialect – The class name of a NHibernate Dialect.
connection.driver_class – The type of a custom IDriver, if using DriverConnectionProvider.
connection.connection_string – Connection string to use to obtain the connection.
show_sql – Write all SQL statements to console. Defaults to FALSE.
Note: For more details, please refer the documentation here.
 
<configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" /> 
</configSections>
<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.driver_class>NHibernate.Driver.SqlClientDriver</property
        <property name="connection.connection_string">Data Source=.\SQL2022;Initial Catalog=AjaxSamples;User ID=sa;Password=pass@123;</property
        <property name="show_sql">true</property
        <mapping assembly="NHibernate_ASPNet/> 
    </session-factory>
</hibernate-configuration>
 
 

HTML Markup

The HTML Mark consists of following control:
GridView – For displaying data.

Columns

The GridView consists of three BoundFIeld columns.
<asp:GridView ID="gvCustomersrunat="server" AutoGenerateColumns="false"> 
     <Columns>
         <asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
         <asp:BoundField DataField="Name" HeaderText="Name" />
         <asp:BoundField DataField="Country" HeaderText="Country" />
     </Columns>
 </asp:GridView>
 
 

Namespaces

You will need to import the following namespaces.
C#
using NHibernate;
using NHibernate.Cfg;
 
VB.Net
Imports NHibernate;
Imports NHibernate.Cfg;
 
 

Selecting records using NHibernate in C# and VB.Net

Inside the Page_Load event handler, first the Configuration class object is created which is being configured using its Configure method.
Then, an instance of ISessionFactory interface is initiated where BuildSessionFactory method of Configuration class is called which basically gathers the meta-data.
Note: meta-data is nothing but contains information of assembly reference and other standaralized information such as type definition.
 
After that, ISession object is initialized and OpenSession method of ISessionFactory is called which is used to explicitly close and flush session object when it is done.
Transaction is initiated using BeginTransaction method of ISession interface.
A Generic List collection of Customer class is created and using CreateCriteria method of ISession interface, the records are fetched from the database and the Commit method of ITransaction interface is called.
Finally, the Generic List collection of Customer class is assigned to the DataSource property of the GridView and the GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
 {
     if (!this.IsPostBack)
     {
         Configuration_configuration = new Configuration();
         configuration.Configure();
         using (ISessionFactory sessionFactory _configuration.BuildSessionFactory())
         {
             using (ISession session = _sessionFactory.OpenSession())
             {
                 using (ITransaction tran _session.BeginTransaction())
                 {
                     List<Customer> customers = (List<Customer>)session.CreateCriteria<Customer>().List<Customer>();
                     tran.Commit();
                     gvCustomers.DataSource = customers;
                     gvCustomers.DataBind();
                 }
             }
         }
     }
 }
 
VB.Net
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim configuration As Configuration = New Configuration()
        configuration.Configure()
        Using_sessionFactory As ISessionFactory configuration.BuildSessionFactory()
            Using session As ISession = _sessionFactory.OpenSession()
                Using tran As ITransaction = _session.BeginTransaction()
                    Dim customers As List(Of Customer) = CType(_session.CreateCriteria(Of Customer)().List(Of Customer)(), List(Of Customer))
                    tran.Commit()
                    gvCustomers.DataSource = customers
                    gvCustomers.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub
 
 

Screenshot

Using NHibernate in ASP.Net using C# and VB.Net
 
 

Downloads