Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents (.hbm.xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
How does Fluent NHibernate work?
- It moves your mappings into actual code, so they're compiled along with the rest of your application
- Rename refactorings will alter your mappings just like they should, and the compiler will fail on any typos
- It has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things
- you set how things should be named once, then Fluent NHibernate does the rest
For more info, click the following link: http://wiki.fluentnhibernate.org/
GETTING STARTED:
First thing you need to download NHibernateFluent libraries that can be found here: http://fluentnhibernate.org/
Unzip downloaded file and extract it into a folder of your choice.
Now start Visual Studio and create new windows application project. I named it SimpleOrmApplication. First of all we are going to reference some dll files that Fluent NHibernate needs. Right click on the References in your solution explorer and select Add Reference. Navigate to directory where you have previously extracted your Fluent NHibernate libraries and reference the following dll files:
- FluentNhibernate.dll
- NHibernate.dll
- NHibernate.ByteCode.Castle
Now open our Form1 class in code view and add the following using statements at the top of the class:
using FluentNHibernate; using NHibernate; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using FluentNHibernate.Automapping; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; using NHibernate.Criterion; using SimpleOrmApplication.Model;
Let's continue with creating our database model... At this stage you have number of options how to define and create your model and a number of tools to help you do that, but I have decided that we are going to keep things as simple as possible. In this tutorial won't create our database entities model with designer, instead our model will be represented only by strongly typed C# classes. So for purpose of this tutorial we are going to create two simple classes named Employee and Post, but before that let us add few new folders to our solution, just to keep things organized. Click on your project in solution explorer and add new folder named Model. The classes I mentioned previously will be created inside this newly created folder, so your structure should look something like this:

Your Post class should look like this:
using System;
namespace SimpleOrmApplication.Model
{
public class Post
{
public virtual int Id { get; set; }
public virtual string PostCode { get; set; }
public virtual string PostName { get; set; }
}
}
Your Employee class should look like this:
using System;
namespace SimpleOrmApplication.Model
{
public class Employee
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Address { get; set; }
public virtual Post Post { get; set; }
public virtual DateTime DateEmployed { get; set; }
}
}
Notice that the namespace of this two classes above is SimpleOrmApplication.Model and is named according to our folder structure. This will be important later when we will be creating auto-mappings. I suggest you allways put your database entity classes (like Employee and Post) in a seperate namespace.
Now get back to our Form1 and open it in code view. Add the private static variable of type ISessionFactory and name it sessionFactory. Then add the three methods as shown in code below:
using statements...
...
...
namespace SimpleOrmApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static ISessionFactory BuildSessionFactory()
{
//This method build our session factory -
//the most important part of our ORM application
}
private static AutoPersistenceModel CreateMappings()
{
//This method will create our auto-mappings model
}
private static void BuildSchema(Configuration config)
{
//This method will create/recreate our database
//This method should be called only once when
//we want to create our database
}
private static ISessionFactory sessionFactory;
}
}
Update the CreateMappings method with the following code:
private static AutoPersistenceModel CreateMappings()
{
return AutoMap
.Assembly(System.Reflection.Assembly.GetCallingAssembly())
.Where(t => t.Namespace == "SimpleOrmApplication.Model");
}
This method generates auto-mappings for all the classes (entities) that are found in our SimpleOrmApplication.Model namespace. This is the reason why we needed to place our entity classes in its own namespace, that Fluent NHibernate will map only classes contained in this namespace.
Now update our BuildSchema method to look like the code below:
private static void BuildSchema(Configuration config)
{
new SchemaExport(config).Create(false, true);
}
The last thing we need to do is to configure our Fluent NHibernate, tell it what database provider to use, how to connect to our database and build the session factory. To do this, update the BuildSessionFactory method with the following code:
private static ISessionFactory BuildSessionFactory()
{
AutoPersistenceModel model = CreateMappings();
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(c => c
.Server("MYCOMPUTER\\SQLEXPRESS")
.Database("testdb")
.Username("test")
.Password("test")))
.Mappings(m => m
.AutoMappings.Add(model))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
As you can see, we are using Microsoft SQL server 2005 database. If you wanted to use SQL Server 2008 database you only need to change the second line of return statement to look like this: MsSqlConfiguration.MsSql2008 or MsSqlConfiguration.MsSql2000 if you want to use older versions of SQL Server. There are listed all the database providers that are supported by NHibernate:
* Microsoft SQL Server 2008/2005/2000
* Oracle
* Microsoft Access
* Firebird
* PostgreSQL
* DB2 UDB
* MySQL
* SQLite
If you wanted to use the latest PostgreSql 8.4 database , your BuildSessionFactory method would look like this (the rest of the methods stay unchanged):
private static ISessionFactory BuildSessionFactory()
{
AutoPersistenceModel model = CreateMappings();
return Fluently.Configure()
.Database(PostgreSQLConfiguration.PostgreSQL82
.ConnectionString(c => c
.Host("localhost")
.Port(5432)
.Database("testdb")
.Username("test")
.Password("test")))
.Mappings(m => m
.AutoMappings.Add(model))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
If you use older PostgreSql database just change the second line of return statement to look like this: .Database(PostgreSQLConfiguration.PostgreSQL81
Finally add a button to our form and name it btnDoSomeStuff. Double click the button so the VS creates our btnDoSomeStuff_Click method and add in the following code:
private void btnDoSomeStuff_Click(object sender, EventArgs e)
{
using (ISession session = sessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
Post p1 = new Post();
p1.PostCode = "1000";
p1.PostName = "Ljubljana";
Post p2 = new Post();
p2.PostCode = "2000";
p2.PostName = "Maribor";
Employee emp = new Employee();
emp.FirstName = "Alex";
emp.LastName = "Kecman";
emp.Address = "Sarhova 34";
emp.Post = p2;
emp.DateEmployed = DateTime.Now;
session.Save(emp);
session.Save(p1);
session.Save(p2);
transaction.Commit();
}
}
}
Of course we need to call our BuildSessionFactory method, so update the form's constructor code to look like this.
public Form1()
{
InitializeComponent();
sessionFactory = BuildSessionFactory();
}
Before we start our application, there is only one thing left to do... Whether you are creating PostgreSql or SQL Server database (I haven't tested other db providers), you first need to create empty database with no tables in it (Use the PgAdmin or SQL Server Management to do so), so the NHibernate can find its name and recreate it. Be sure to set the owner of the database to user that you specified in your connection parameters within BuildSessionFactory method.
Now we are good to take our application for the first test.
Below I provided few more NHibernate queries, just to get you started. Refere to NHibernate documentation for more info...
private void btnDoSomeStuff_Click(object sender, EventArgs e)
{
using (ISession session = sessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
//Get post with id == 2
int id_post = 2;
Post p1 = session.Get<Post>(id_post);
//Get employee with id == 1
int id_employee = 1;
Employee emp = session.Get<Employee>(id_employee);
//Get a list of all posts
IList<Post> posts = session
.CreateCriteria(typeof(Post))
.List<Post>();
//Get a post by given name
string post_name = "Maribor";
Post p2 = session.CreateCriteria(typeof(Post))
.Add(Expression.Eq("PostName", post_name))
.UniqueResult<Post>();
}
}
}
I hope you enjoyed this tutorial. If you have any question, feel free to ask...




MultiQuote






|