joydip_kanjilal
Contributor

How to work with Fluent NHibernate in C#

opinion
Feb 04, 20164 mins
Software Development

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

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]

(

   [Id] INT NOT NULL PRIMARY KEY,

   [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 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);

           Table("Product");

       }

   }

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()

               .Database(MsSqlConfiguration.MsSql2012

                 .ConnectionString(connectionString).ShowSql()

               )

               .Mappings(m =>

                         m.FluentMappings

                             .AddFromAssemblyOf<Product>())

               .ExposeConfiguration(cfg => new SchemaExport(cfg)

                .Create(false, false))

               .BuildSessionFactory();

           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" };

               session.SaveOrUpdate(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.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author