How to work with Fluent NHibernate in C#

Fluent NHibernate provides a Fluent API also enables you to use LINQ to query data on top of the NHibernate engine

Fluent NHibernate

ORMs (object relational mappers) simplify data access in your application by allowing you to write code to perform CRUD (Create, Read, Update, and Delete) operations. ORM frameworks have been in use for a long time to eliminate the impedance mismatch that exists between the object and data models in an application. In essence, ORMs enable you to write code to perform CRUD operations sans the need of interacting with the underlying database provider directly. Thus, usage of ORMs help you to isolate the object model of your application from the data model.

Why Fluent NHibernate?

NHibernate stores the mapping information in XML format in .hbm files -- you should have one .hbm file for each entity class. This .hbm file is used to map the entities to the corresponding database tables. In using Fluent NHibernate, you no longer need to use the cumbersome .hbm.xml files that you have had to use when working with NHibernate.

Fluent NHibernate is the statically compiled, compile safe counterpart of the popular ORM tool NHibernate that can be used to create mapping between the POCO classes and NHibernate engine sans the need of cumbersome XML files. It provides a Fluent API also enables you to use LINQ to query data on top of the NHibernate engine. In the sections that follow, we will discuss how we can install Fluent NHibernate, create models, map these models or entity classes and use Fluent NHibernate to perform CRUD operations.

Getting started

To get started using Fluent NHibernate, follow these steps:

  1. Open Visual Studio 2015 IDE
  2. Click on File -> New -> Project
  3. Create a new project – for the sake of simplicity, create a Windows Application
  4. Specify a name for the project
  5. Click OK to save the project

Now that a project has been created in Visual Studio, you may want to install Fluent NHibernate to use it in your application. If you have NuGet installed, the easiest option is to install Fluent NHibernate via the NuGet Package Manager. To do this select the project in the Solution Explorer Window, right click and select "Manage NuGet Packages…" option to install Fluent NHibernate framework from NuGet.

Working with Fluent NHibernate

To work with Fluent NHibernate you would first need to create a model class. Consider the following database table.

CREATE TABLE [dbo].[Product]



   [Name] VARCHAR(50) NULL,

   [Description] VARCHAR(50) NULL


Here's the corresponding model class.

public class Product


       public virtual int Id { get; set; }

       public virtual string Name { get; set; }

       public virtual string Description { get; set; }


Now that the database table and the corresponding model class is ready, the next step is to create the necessary mapping. To map an entity in Fluent NHibernate you should have a corresponding mapping class. Such mapping classes should derive from ClassMap<T> where T represents the entity you are using. Fluent NHibernate uses strongly typed C# classes to map the properties of the model classes to the corresponding fields of the database tables.

Here's the mapping class named ProductMap.

public class ProductMap : ClassMap<Product>


       public ProductMap()


           Id(x => x.Id);

           Map(x => x.Name);

           Map(x => x.Description);




The next step is to create a helper class to connect to our database. Here's what this class would look like:

public static class FluentNHibernateHelper


       public static ISession OpenSession()


string connectionString = "Write your database connection string here";

           ISessionFactory sessionFactory = Fluently.Configure()




               .Mappings(m =>



               .ExposeConfiguration(cfg => new SchemaExport(cfg)

                .Create(false, false))


           return sessionFactory.OpenSession();



Note the call to the sessionFactory.OpenSession() in the last statement -- this call actually creates a session of communication with the underlying database, i.e., it opens a connection to the database in use. You can now invoke the static method FluentNHibernateHelper.OpenSession() to open a connection to the database. The following code snippet illustrates how you can take advantage of the helper class created earlier to add a Product record to the Product database table.

static void Main(string[] args)


           using (var session = FluentNHibernateHelper.OpenSession())


               var product = new Product { Name = "Lenovo Laptop", Description = "Sample product" };




The following code snippet shows how you can query data from the database using our Fluent NHibernate helper class.

using (ISession session = FluentNHibernateHelper.OpenSession())


               var products = session.Query<Product>().ToList();

               //Usual code


To work with the code examples given in this article, you should ensure that the following namespaces have been added to your class.

  • using FluentNHibernate.Cfg;
  • using FluentNHibernate.Cfg.Db;
  • using NHibernate;
  • using NHibernate.Linq;
  • using NHibernate.Tool.hbm2ddl;
  • using System.Linq;

You can learn more on working with Fluent NHibernate from GitHub.

Copyright © 2016 IDG Communications, Inc.

InfoWorld Technology of the Year Awards 2023. Now open for entries!