RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Using Fluent NHibernate for XML-Free Class Mapping

Fluent NHibernate lets you map .NET classes with NHibernate without the need for those cumbersome XML files.


NHibernate, the lightweight object relational mapping (ORM) tool for .NET, has a statically compiled counterpart called Fluent NHibernate. In essence, Fluent NHibernate is a XML-less, compile safe, automated NHibernate mapper that provides support for LINQ on top of NHibernate as well as an alternative to NHibernate's standard XML mapping.

In this article I will discuss the basics of Fluent NHibernate, how to get started using it, and how you can implement various types of mappings in your .NET applications using this lightweight ORM tool.

To use the code examples illustrated in this article, you should have Visual Studio 2008 or higher installed on your system. You should also have the necessary NHibernate and Fluent NHibernate assemblies available. You can download them from the Fluent NHibernate webpage.

Getting Started with Fluent NHibernate

To get started with Fluent NHibernate, you need to create a new project in Visual Studio 2010 and then add the necessary assemblies. The following sample program lists those assemblies and also illustrates how you can open a connection to your SQL Server database using Fluent NHibernate. This class acts as a wrapper on top of Fluent NHibernate.

using FluentNHibernate;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System.Reflection;
namespace Test
    public static class FluentNHibernateGateway
        private static ISessionFactory _sessionFactory = null;
        private static readonly string _businessObjectsNamespace = "Test.BusinessEntity.Mappings";
        private static readonly string _connectionString = @"Data Source=JOYDIP-PC\SQLServer2008;Initial Catalog=Sample;Integrated Security=True";
        private static ISessionFactory SessionFactory
                if (_sessionFactory == null)
//Code to create a new session factory 
//using the persistence model and loading the 
// business entities from the namespace 
//specified earlier in this program.
             return _sessionFactory;
        public static ISession OpenSession()
            return SessionFactory.OpenSession();

Now, to open a connection and get started, you would call FluentNHibernateGateway.OpenSession();.

And, that's all -- you can then play around with Fluent NHibernate and perform CRUD operations on your database as needed. Next, learn how to implement mappings using Fluent NHibernate.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date