February 28, 2021
Hot Topics:

Using NHibernate as an ORM Solution for .NET

  • By David Consdorf
  • Send Email »
  • More Articles »

This class creates and manages a static instance of the session factory for an application. The static constructor reads in the configuration from the web.config file, adds the mappings to it, and then uses the configuration to create a session factory.

Also note how the GetCurrentSession() method stores and retrieves the session in the HttpContext. In web applications, NHibernate often uses the session per request model. This means that one session is created for each request and it is re-used for the duration of the request. When you call GetCurrentSession() the first time during a request, it creates the session and stores it in the context. Each subsequent call to GetCurrentSession() returns the same session stored in the context. The CloseSession() method isn't called until the Application_EndRequest method of the Global.ascx file.

The session per request model becomes especially important because the session may be used to keep track of the state of an object and what needs to be updated when saving the object. It is also used for lazy loading; I will talk about this in more detail later in the article.

Using NHibernate to Retrieve Objects

Now that you have a mechanism for creating sessions, look at a get call for the Customer class:

public static Customer getCustomer(int? customerID)
   // Open the session
   ISession session = NHibernateHelper.GetCurrentSession();

      // Load the order from the database
      Customer customer = (Customer)session.Load(typeof(Customer),

      return customer;

Listing 6: Sample Application—Simple Object Retrieval

In this method, you simply get the session instance and then load in the Customer object for the ID defined. This will automatically go to the database and load in whatever data is required to the fill the Customer object with the data from the database.

As was discussed earlier, you don't close the session in this method because it will be closed in the Application_EndRequest method.

You also can perform more complex queries by using an NHibernate ICriteria object. For example, look at the ProductOrder method to retrieve product orders for a specific customer:

public static List<ProductOrder>
   getProductOrdersForCustomer(int? customerID)
   List<ProductOrder> orders = new List<ProductOrder>();

   // Get the session
   ISession session = NHibernateHelper.GetCurrentSession();

   // Load the order from the database
   ICriteria criteria = session.CreateCriteria(typeof(ProductOrder));
      criteria.Add(Expression.Eq("CustomerID", customerID));

   return orders;

Listing 7: Sample Application—Object Retrieval By Criteria

An ICriteria object basically builds a where clause programmatically. First, you specify that you are creating a criteria object for a certain object type, in this case ProductOrder, and then you add criteria with the Expression class. This will return all ProductOrder objects that match the specified criteria. This is a simple example with a single equals criteria where the CustomerID property of the ProductOrder needs to match the customerID specified. For more complex queries, there are several other types of expressions similar to what you would see in the where clause of an SQL query (Less Than, Greater Than, Like, Between, and so forth).

If using a criteria object doesn't suit you, you also can use HQL. HQL is NHibernate's custom query language for dealing with object queries. Here are a few HQL query examples:

  • "from ProductOrder o": Returns all ProductOrder objects.
  • "from ProductOrder o where o.CustomerID = ?": Returns the ProductOrder objects ordered by a specific customer.
  • "select distinct o.ProductName from ProductOrder o": Returns the name of all products ordered.
  • "select distinct o.ProductName from ProductOrder o where o.CustomerID = ?": Returns the name of all products ordered by a specific customer.

Using NHibernate to Save, Update, and Delete Objects

Now, look at an example for saving/updating an object. Here is the method for saving/updating a customer:

public static void saveOrUpdateCustomer(Customer customer)
   ISession session = NHibernateHelper.GetCurrentSession();
   ITransaction transaction = null;

      // Start transaction
      transaction = session.BeginTransaction();

      // Save or update (saves if id is null; otherwise, updates)

      // Commit transaction
   catch (Exception ex)
      throw ex;

Listing 8: Sample Application—Saving/Updating Objects

Page 5 of 6

This article was originally published on November 6, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date