Fluent Nhibernate Made Easy

fluent-nhibernate

Progressing from using NHibernate to Fluent NHibernate is a practical way of not using XML files. For people like me, who are not very comfortable using XML files, Fluent NHibernate gives the opportunity to map your domain class entities through traditional C# classes. So lets start by specifying the requirements to complete this tutorial:

Requirements for this Tutorial:

  • NuGet Package Manager (unless you already have Fluent NHibernate)
  • Visual Studio 2010
  • MS SQL 2005 or 2008

Note: If you have never used NHibernate at all, I suggest you start from my previous tutorial NHibernate made easy

This tutorial will be very similar the the previous one, however it will include all changes required to use Fluent NHibernate rather than NHibernate.

Step 1:- Create a 2-Thier Project

1. New Web Application and name solution to “MyFirstFluentNhibernate”

2. Add a new Class Library project to the solution and name it “DataLayer” which will be used to connect to the database through Nhibernate

3. Rename the Web Layer to “PresentationLayer” and add reference to the “DataLayer” Project

4. In the “DataLayer” Class Library add the following folders:

– Domain (will contain classes to represent tables and their properties in the database)

– Mappings  (will contain classess to map to tables in database through Fluent Nhibernate)

– Repositories (method implementation for Select, Insert, Update and Delete in tables of the database)

Step 2:- Install Nhibernate

Nhibernate has to be installed for both Thiers. Make sure you install NuGet to be able to complete this step:

Visual Studio Tools >> Library Package Manager >> Manage NuGet Packages for Solution >> type “Fluent Nhibernate” >> Add Fluent Nhibernate

Step 3:- Define Business Objects (Domain Folder)

In the folder “Domain”, add a new class and name it “Book.cs” and copy the following properties:

public class Book
{
public virtual Guid Id { get; set; }
public virtual string Title { get; set; }
public virtual string Author { get; set; }
}

Step 4:- Define the Mapping (Mappings Folder)

Add a new class and name it BookMap.cs which will map the Book class in the Domain with the Book table in the database.

Add the following references:

using FluentNHibernate.Mapping;
using DataLayer.Domain;

Make the class public and inherit from ClassMap<Book>

Add the following constructor in the class:

public BookMap()
{
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.Author);


Table(“Book”);


}

So, this class should look like something like this:


using FluentNHibernate.Mapping;
using DataLayer.Domain;


namespace DataLayer.Mappings
{
public class BookMap : ClassMap<Book>
{
public BookMap()
{
Id(x => x.Id);
Map(x => x.Title);
Map(x => x.Author);


Table(“Book”);


}
}
}

Note 1:

if you need to reference a many-t0-many relationship, then the right way to reference it is to add the following mapping in the constructor:
References(x => x.BookGenre).Column(“GenreId”);  //x.Genre is our column in the current table, and GenreId is the referencing column (usually Primary ID)  in the other Table

and the following property to the domain class:
public virtual Genre BookGenre{get; set;} // Represent the relation between Book and Genre

Note 2:

if you need a list then we add the following in the constructor:
HasMany<Character>(x => x.Characters);

and the following property to the domain class:
public virtual IList<Character> Characters{ get; set; }

where Character would be another Table ( it also need a class in the domain named Character.cs )

Step 5:- Create ISessionFactory with Nhibernate Configuration to SQL Server 2008 (NhibernateHelper)

Create a new class in the main directory of the Class Library and name it “NhibernateHelper.cs” which will create a session factory when the client makes his first request a new session (ONLY ONCE)

Add the following references to the NhibernateHelper class:

using NHibernate;
using NHibernate.Cfg;
using DataLayer.Domain;

Make sure the class is made public and copy the following ISessionFactory methods:

private static ISessionFactory _sessionFactory;


//Create Connection without generating Schema
private static ISessionFactory SessionFactoryBook
{
get
{
if (_sessionFactory == null)
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(connString())
.ShowSql()
)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<Book>())
.BuildSessionFactory();
}
return _sessionFactory;
}
}


//Open Session (Method to Call)
public static ISession OpenSessionBook()
{
return SessionFactoryBook.OpenSession();
}


//Create Connection and generate Schema (create table)
private static ISessionFactory SessionFactoryBookCreateSchema
{
get
{
if (_sessionFactory == null)
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(connString())
.ShowSql()
)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<Book>())
.ExposeConfiguration(cfg => new NHibernate.Tool.hbm2ddl.SchemaExport(cfg)
.Create(true, true))
.BuildSessionFactory();
}
return _sessionFactory;
}
}

//Open Session with create schema properties

public static ISession OpenSessionBookCreateSchema()
{
return SessionFactoryBookCreateSchema.OpenSession();
}


//default connection string to be used by both Sessions above
private static string connString()
{
return @”Server=***.***.***.***;Initial Catalog=*****;MultipleActiveResultSets=True;Persist Security Info=True;User ID=***;Password=***;”;

}

P.S: Do not forget to change IP, CATALOG, USER ID and PASSWORD of connection string

Step 6:- Create Table from Schema and Test Connection

Lets open the Web Application Project which we named “PresentationLayer” and in one of the pages (Default.aspx suggested) add a new button names “btn_Create_Book_Table”

Double-Click the button to create the on_click event in the code behind and simple add the following in the event:

NhibernateHelper.OpenSessionBookCreateSchema();

Note: You will need to reference the following in the code behind:

using DataLayer;
using DataLayer.Domain;

Now, run the page and click the Add button. Verify that the table has been created by refreshing your database in Visual Studio Server Explorer.

The Following steps listed below can be followed from  NHibernate made easy starting from STEP 9 up to STEP 11:

Step 7:- Create Repositories (Domain Folder)

Step 8:- Define Method from Repositories (Repositories Folder)

Step 9:- Testing Select, Add, Update, Delete Method

May you have any queries… I will be glad to help.

Thanks for following … enjoy 🙂

One thought on “Fluent Nhibernate Made Easy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s