Updated March 13, 2023
Introduction to NHibernate fluent
NHibernate Fluent is the alternative way for mapping the data of the tables of the database to the entities or classes in the application code. It is the alternative solution to XML mapping files in standards of NHibernate. We write the files of mapping in C# programming language that is strongly typed instead of writing .hbm.XML mapping files. In this article, we will study what is NHibernate fluent, its associated tools, how it can be used, its setup and installation of the same, and the concluding statement.
What is NHibernate fluent?
NHibernate is the ORM that is an object-relational mapping tool that helps in mapping the data of the tables in the database to the entities of the class in application code and vice versa. The compilation of the mapping files of hibernate happens along with the other applications. We can change the code of the mapping files at any given time but have to be careful as the compiler cannot run with typos and results in errors. We can override the naming conventions and other attributes as by default it has the system of conventional configurations. We can also enable a functionality wherein we will specify the rules and things that should be used in naming conventions and NHibernate fluent manages the rest of the things on its own.
How do I use Nhibernate fluent?
You can make the set of NHibernate by installing the package and adding the required libraries and files in your project code of the application so that you can make use of the features. The installation of NHibernate is very easy provided if you have a Nuget package manager. Thereafter you can create a new project for your application and add the libraries and refer to the libraries of fluent NHibernate to use it in your project.
Nhibernate fluent Tools
NHibernate fluent tools include mapping the data of tables to entities, managing the schema, managing the dependencies, and as an ORM tool. The alternative tools for Fluent NHibernate include NHibernate Analyzer for queries and Fluent NHibernate that enables non-XML mapping of data.
Setup of Fluent NHibernate
In order to do the necessary setup of NHibernate, you can follow the below-mentioned steps. We will be using SQL database; however, you can choose your own database that you will be using in your application.
Step 1 – Creation of the table and the database in which it will reside
Suppose that we have created a database named EducbaNHibernate in our local database of SQL. We will now execute the following command to create a table named Customers –
CREATE TABLE customers_sample
( customer_id int
, f_name VARCHAR(20)
, l_name VARCHAR(25)
, email_id VARCHAR(100)
, mobile_number VARCHAR(20)
, purchase_date DATE
, store_id VARCHAR(20)
, bill_amount int
, salesman_id int
, department_id int
)
We will also insert some records in it using the Insert command –
INSERT INTO customers_sample VALUES (100,'KRITIKA','PALAK','[email protected]','9145685245','17-06-2003','GROCERIES',24000,NULL,NULL)
,(101,'DAKSHA','CHANDWANI','[email protected]','9145685246','21-09-2021','FRUITS',17000,100,90)
,(102,'SHETHS','SINHA','[email protected]','9145685247','13-01-2001','FRUITS',17000,100,90)
,(103,'MAYUR','SACHWANI','[email protected]','9145685248','03-01-2020','VEGETABLES',9000,102,60)
,(104,'MAHESH','SHETH','[email protected]','9145685249','21-05-2021','VEGETABLES',6000,103,60)
,(105,'KARRENA','KAPOOR','[email protected]','9145685250','25-06-2021','VEGETABLES',4800,103,60)
,(106,'AKSHAY','UTALE','[email protected]','9145685251','05-02-2020','VEGETABLES',4800,103,60)
,(107,'PRIYANKA','DUDUSKAR','[email protected]','9145685252','07-02-2021','VEGETABLES',4200,103,60)
,(108,'SHRADDHA','SHINDE','[email protected]','9145685253','17-08-2020','DAILY_ESSESNTIALS',12008,101,100)
,(109,'TEJASHRI','DAPHALE','[email protected]','9145685254','16-08-2020','ELECTRONICS',9000,108,100)
,(110,'MEDHA','KULKARNI','[email protected]','9145685255','28-09-2021','ELECTRONICS',8200,108,100)
,(111,'AISHWARYA','MANE','[email protected]','9145685256','30-09-2021','ELECTRONICS',7700,108,100)
,(112,'MINAL','DESHPANDE','[email protected]','9145685257','07-03-2020','ELECTRONICS',7800,108,100)
,(113,'KENSHA','MATHUR','[email protected]','9145685258','07-12-2021','ELECTRONICS',6900,108,100);
After firing the above commands we can see that our table looks as shown below –
Step 2 – Creation of the Console app in visual studio with the help of .Net framework
You can open the visual studio and then click on the File option at the top, then click on the New, and then select project. You can select the Console app option and assign the name to your project when the dialog box will appear as shown below –
Further click on OK button. Along with that, you can also install the Fluent and NHibernate at this step easily by using the Nuget package. After the addition of these libraries to your project, you will be ready to use the features of NHibernate Fluent.
Step 3 – Creation of new Classes that are entities corresponding to the table
For our table customers sample, we will create the following class file which will act as an entity corresponding to the table that we created.
public class customers_sample
{
public virtual int customer_id {get; set;}
public virtual string f_name {get; set;}
public virtual string l_name {get; set;}
public virtual string email_id {get; set;}
public virtual string mobile_number {get; set;}
public virtual string purchase_date {get; set;}
public virtual string store_id {get; set;}
public virtual string bill_amount {get; set;}
public virtual string salesman_id {get; set;}
public virtual string department_id {get; set;}
public virtual int Id {get; set;}
public virtual string Name {get; set;}
public virtual string Email{get; set;}
}
Step 4 – Mapping file creation to map entities to table.
We will have to map each field in the entity with the corresponding column of the table. For that, we will create a new class file of mapping. For our example, we will create the following file in C#
public class CustomerSampleMapping : ClassMap<customers_sample>
{
public CustomerSampleMapping ()
{
Map(x => x.customer_id );
Map(x => x.f_name );
Map(x => x.l_name );
Map(x => x.email_id );
Map(x => x.mobile_number );
Map(x => x.purchase_date );
Map(x => x.store_id );
Map(x => x.bill_amount );
Map(x => x.salesman_id);
Map(x => x.department_id );
}
}
Step 5 – We will configure the NHibernate
In our case, we will create the following file for configuration –
public class customers_sample
{
public virtual int customer_id );
Map(x => x.f_name );
Map(x => x.l_name );
Map(x => x.email_id );
Map(x => x.mobile_number );
Map(x => x.purchase_date );
Map(x => x.store_id );
Map(x => x.bill_amount );
Map(x => x.salesman_id);
Map(x => x.department_id );
}
class ConfigurationHelperForNHibernate
{
private const string keyForNHibernate = "nhibernate.current_session";
private static readonly ISessionFactory objForSession;
static ConfigurationHelperForNHibernate()
{
objForSession = FluentConfigure();
}
public static ISession GetCurrentSession()
{
return objForSession.OpenSession();
}
public static void CloseSession()
{
objForSession.Close();
}
public static void CloseSessionFactory()
{
if (objForSession! = null)
{
objForSession.Close();
}
}
public static ISessionFactory FluentConfigure()
{
return Fluently.Configure()
. Database (
MsSqlConfiguration.MsSql2012
.ConnectionString(
cs => cs.FromConnectionStringWithKey
("DBConnection"))
)
. Cache (
c => c.UseQueryCache()
.UseSecondLevelCache()
.ProviderClass<NHibernate.Cache.HashtableCacheProvider>())
. Mappings (m => m. FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.BuildSessionFactory();
}
}
The last step to do is to write and read to and from the database tables.
Install nhibernate fluent
In order to install Fluent NHibernate by using Nuget Package Manager Console. For this, you can make the use of the following command –
Install -package FluentNHibernate
You will observe the following output –
Let us consider one example where we will firstly create a simple class for the Model part of MVC named EducbaWriterHiber and will set it in the directory http://localhost/EducbaWriterHiber. We will then add the reference of NHibernate.dll. If you are using Visual Studio editor, then it will automatically copy all the dependencies and libraries in the project. Then you will go for creating the XML file for mapping as shown below –
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="EducbaWriterHiber" namespace="EducbaWriterHiber.Models">
<class name="Educba_writers" table="Educba_writers" dynamic-update="true" xmlns="urn:nhibernate-mapping-2.2">
<cache usage="read-write"/>
<id name="Id" column="writer_id" type="int">
<generator class="native" />
</id>
<property name="f_name" />
<property name="l_name" />
<property name="email_id" />
<property name="mobile_number" />
<property name="join_date" />
<property name="domain_id" />
<property name="pay_amount" />
<property name="guide_id" />
<property name="department_id" />
</class>
</hibernate-mapping>
Now, we will create a new configuration file hibernate.cfg.xml, or register the entry in Web. config. Thereafter, you can create the POCO file named Educbawriter as shown below –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EMPNHibernate.Models
{
public class Employee
{
public virtual int writer_id { get; set; }
public virtual string f_name { get; set; }
public virtual string l_name { get; set; }
public virtual string email_id { get; set; }
public virtual string mobile_number { get; set; }
public virtual string join_date { get; set; }
public virtual string domain_id { get; set; }
public virtual string pay_amount { get; set; }
public virtual string guide_id" />
public virtual string department_id" />
}
}
Now, we will create the main class of ASX page that can be used as a singleton class having NHibernate session factory class in it –
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn: nhibernate-mapping-2.2" auto-import="true" assembly="EducbaWriterHiber" namespace="EducbaWriterHiber.Models">
<class name="Educba_writers" table="Educba_writers" dynamic-update="true" xmlns="urn:nhibernate-mapping-2.2">
<cache usage="read-write"/>
<id name="Id" column="writer_id" type="int">
<generator class="native { get; set; }
</id>
public virtual string f_name { get; set; }
public virtual string l_name { get; set; }
public virtual string email_id { get; set; }
public virtual string mobile_number { get; set; }
public virtual string join_date { get; set; }
public virtual string domain_id { get; set; }
public virtual string pay_amount { get; set; }
public virtual string guide_id" />
public virtual string department_id" />
</class>
</hibernate-mapping>
Create an entry in Web.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EMPNHibernate.Models
{
public class Educba_writers
{
public virtual int writer_id { get; set; }
public virtual string f_name { get; set; }
public virtual string l_name { get; set; }
public virtual string email_id { get; set; }
public virtual string mobile_number { get; set; }
public virtual string join_date { get; set; }
public virtual string domain_id { get; set; }
public virtual string pay_amount { get; set; }
public virtual string guide_id" />
public virtual string department_id" />
}
}
using System.Web;
using NHibernate;
using NHibernate.Cfg;
namespace EducbaWriterHiber
{
public class EducbaWriterHiberSession
{
public static ISession OpenSession()
{
var sampleConfig = new Configuration();
sampleConfig.Configure();
ISessionFactory sampleSessFactory = sampleConfig.BuildSessionFactory();
return sampleSessFactory.OpenSession();
}
}
}
The last thing will be to close the session –
You can see your output being converted as shown below –
Conclusion
NHibernate Fluent is the standard ORM that is an object-relational mapping tool that is used for mapping the data of the tables to entities and vice versa. It is specially created for .Net framework and works with the C# programming language.
Recommended Articles
This is a guide to NHibernate fluent. Here we discuss the Introduction, What is NHibernate fluent, How do I use nhibernate fluent?. You may also have a look at the following articles to learn more –