Configuration of Fluent NHibernate through C# code

Ahamed Fazil Buhari
Senior Developer
November 27, 2017
Rate this article
[Total: 1    Average: 5/5]

Hello everyone,

In this article we will see how to configure Fluent NHibernate through C# code, it gives easy way to query, save or update data on Database and it lies on top of NHibernate engine. Please refer this link to know more about Fluent NHibernate.

First and foremost, add fluent nhibernate reference to your project with the help of NuGet Package,




Provide details on Database and Server name through traditional way, connectionString in app.config file

     <add name="db" connectionString="Data Source=serverName;database=dbName;Integrated Security=True;" />

In the code call a function that will instantiate the configuration and fluent nhibernate configuration done through code not with the help of config file.

 using Ncfg = FluentNHibernate.Cfg;
 public static class DataBaseOperation
         private static ISessionFactory _sessionFactory;
         public static void DataBase_Open()
             var connString = ConfigurationManager.ConnectionStrings["db"].ToString();
             _sessionFactory = Ncfg.Fluently.Configure()
                 .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TablePackage>())
                 .ExposeConfiguration(cfg =>
                     cfg.SetProperty("adonet.batch_size", "100");
                     new SchemaUpdate(cfg).Execute(false, true);
        // If you want to overwrite and create new table, then uncomment the below line
                 //.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))

There are 3 things we need to setup before configuring. One is connectionString, second is Domain layer (class which contains filed names) and mapping class.

 public class TablePackage
         public virtual string ID { get; set; }     
         public virtual string Status { get; set; }
         public virtual DateTime CreationDate { get; set; }
 TableMapping.cs – Mapping class should extend ClassMap<> FluentNHibernate class
 using FluentNHibernate.Mapping;
     public class TableMapping : ClassMap<TablePackage>
         public TableMapping()
             Id(x => x.ID).GeneratedBy.Assigned();//.GeneratedBy.Increment();
             Map(x => x.Status);
             Map(x => x.CreationDate);

In the upcoming article we will see how to deal with data using Fluent NHibernate.


Happy Coding


Author Info

Ahamed Fazil Buhari
Senior Developer
Rate this article
[Total: 1    Average: 5/5]
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint 2013, 2016 and O365, Azure, ASP.NET, SQL Server, IIS and client more

Leave a comment