Configuration of Fluent NHibernate through C# code

Ahamed Fazil Buhari
SharePoint Developer
Published On :   27 Nov 2017
Visit Count
Today :  5    Total :   363
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

SharePoint Office 365 Tool
Simple & Powerful Tool for Migration, Security & Reporting. Free Trial

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


SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.

Migratiin Tools for SharePoint