How to use Fluent NHibernate in C#

By FoxLearn 1/7/2025 2:45:23 AM   114
Fluent NHibernate is an Object-Relational Mapping (ORM) framework that simplifies data access by allowing developers to perform CRUD (Create, Read, Update, Delete) operations without directly interacting with the database.

It provides a Fluent API for easier configuration and enables LINQ queries on top of NHibernate. ORMs help resolve the mismatch between object models in code and the relational data models in databases, isolating the application's object model from the underlying data model for more efficient and maintainable code.

Benefits of Fluent NHibernate

NHibernate traditionally stores mapping information in XML format using .hbm files one for each entity class. These files are used to map entities to corresponding database tables. However, with Fluent NHibernate, you no longer need to work with these cumbersome .hbm.xml files.

Fluent NHibernate is a statically compiled, compile-safe alternative to NHibernate that simplifies the mapping between POCO classes and the NHibernate engine, eliminating the need for XML files. It offers a Fluent API and also supports LINQ queries on top of NHibernate. In the following sections, we will explore how to install Fluent NHibernate, create models, map them to entity classes, and use Fluent NHibernate to perform CRUD operations.

Installing Fluent NHibernate in Your Project

Once you’ve created your project in Visual Studio, the next step is to install Fluent NHibernate to use in your application.

If you have NuGet installed, the simplest method is through the NuGet Package Manager. To do this, right-click the project in the Solution Explorer and select the "Manage NuGet Packages…" option to install Fluent NHibernate directly from NuGet.

Working with Fluent NHibernate

To get started with Fluent NHibernate, the first thing you need is a model class. For example, suppose you have a Customer table in your database like this:

CREATE TABLE [dbo].[Customer]
(
    [Id] INT NOT NULL PRIMARY KEY,
    [Name] VARCHAR(50) NULL,
    [Email] VARCHAR(50) NULL
)

The corresponding model class would look like this:

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Email { get; set; }
}

Creating the Mapping Class

Next, you'll need to create the mapping class that connects your Customer class to the Customer table in the database. In Fluent NHibernate, this is done by creating a class that derives from ClassMap<T>, where T is the entity you are mapping.

Here’s how the CustomerMap class would look:

public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        Id(x => x.Id);                // Maps the 'Id' property
        Map(x => x.Name);              // Maps the 'Name' property
        Map(x => x.Email);             // Maps the 'Email' property
        Table("Customer");             // Specifies the database table name
    }
}

Creating the Database Connection Helper

After the mapping is defined, you need to create a helper class to open a session and connect to the database.

public static class FluentNHibernateHelper
{
    public static ISession OpenSession()
    {
        string connectionString = "Your database connection string here";

        ISessionFactory sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2012
                .ConnectionString(connectionString)
                .ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Customer>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)
                .Create(false, false))
            .BuildSessionFactory();

        return sessionFactory.OpenSession();
    }
}

In this helper class, note the call to sessionFactory.OpenSession(), which opens a session and establishes communication with the database.

Inserting a Record

Now that your database connection and mappings are ready, you can insert data into the Customer table using the helper class.

static void Main(string[] args)
{
    using (var session = FluentNHibernateHelper.OpenSession())
    {
        var customer = new Customer { Name = "John Doe", Email = "[email protected]" };
        session.SaveOrUpdate(customer);   // Saves or updates the record in the database
    }
}

Querying Data

You can also query data from the database using Fluent NHibernate.

using (ISession session = FluentNHibernateHelper.OpenSession())
{
    var customers = session.Query<Customer>().ToList();
    // Perform any additional operations with the 'customers' list
}

Required Namespaces

To ensure your code works correctly, add the following namespaces:

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

These namespaces provide the necessary classes and methods to configure Fluent NHibernate, interact with the database, and perform LINQ queries.