How to work with Fluent NHibernate in C#

Fluent NHibernate provides a Fluent API besides enables yous to utilize LINQ to query data on top of the NHibernate engine

Fluent NHibernate

ORMs (object relational mappers) simplify information admission in your application by allowing y'all 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 betwixt 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 direct. Thus, usage of ORMs help yous 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 course. This .hbm file is used to map the entities to the respective 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. Information technology 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 hash out 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 go 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 relieve 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 Packet Manager. To practice this select the project in the Solution Explorer Window, right click and select "Manage NuGet Packages…" selection to install Fluent NHibernate framework from NuGet.

Working with Fluent NHibernate

To work with Fluent NHibernate you would starting time need to create a model course. Consider the following database tabular array.

CREATE TABLE [dbo].[Product]

(

   [Id] INT Not NULL PRIMARY Fundamental,

   [Name] VARCHAR(50) Nothing,

   [Description] VARCHAR(50) NULL

)

Here's the corresponding model class.

public form Product

   {

       public virtual int Id { get; fix; }

       public virtual string Name { get; set up; }

       public virtual string Description { become; ready; }

   }

At present that the database table and the corresponding model form is ready, the next footstep is to create the necessary mapping. To map an entity in Fluent NHibernate you should have a corresponding mapping course. Such mapping classes should derive from ClassMap<T> 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 respective fields of the database tables.

Here's the mapping class named ProductMap.

public grade ProductMap : ClassMap<Product>

   {

       public ProductMap()

       {

           Id(x => 10.Id);

           Map(ten => x.Proper name);

           Map(x => x.Description);

           Table("Production");

       }

   }

The side by side step is to create a helper form to connect to our database. Here'southward what this class would look like:

public static class FluentNHibernateHelper

   {

       public static ISession OpenSession()

       {

string connectionString = "Write your database connectedness string here";

           ISessionFactory sessionFactory = Fluently.Configure()

               .Database(MsSqlConfiguration.MsSql2012

                 .ConnectionString(connectionString).ShowSql()

               )

               .Mappings(g =>

                         m.FluentMappings

                             .AddFromAssemblyOf<Production>())

               .ExposeConfiguration(cfg => new SchemaExport(cfg)

                .Create(false, false))

               .BuildSessionFactory();

           return sessionFactory.OpenSession();

       }

   }

Note the call to the sessionFactory.OpenSession() in the final statement -- this phone call really creates a session of communication with the underlying database, i.e., information technology opens a connexion to the database in apply. You can now invoke the static method FluentNHibernateHelper.OpenSession() to open a connexion to the database. The following code snippet illustrates how y'all can take reward of the helper class created earlier to add a Product record to the Product database tabular array.

static void Master(string[] args)

       {

           using (var session = FluentNHibernateHelper.OpenSession())

           {

               var product = new Product { Name = "Lenovo Laptop", Clarification = "Sample production" };

               session.SaveOrUpdate(product);

           }

       }

The following code snippet shows how you tin query data from the database using our Fluent NHibernate helper class.

using (ISession session = FluentNHibernateHelper.OpenSession())

           {

               var products = session.Query<Product>().ToList();

               //Usual lawmaking

           }

To piece of work with the lawmaking examples given in this commodity, y'all 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 Arrangement.Linq;

Yous can larn more on working with Fluent NHibernate from GitHub.

Copyright © 2016 IDG Communications, Inc.