Saturday, December 26, 2009

Fluent NHibernate Tutorial

Note: This post is based on NHibernate version 2.1 with Fluent NHibernate version 1.0 RTM.

This tutorial introduces Fluent NHibernate. Fluent NHibernate is a "code oriented" alternative to configuring NHibernate maping using XML configuration files.

This tutorial is based on same project entities defined in my previous NHibernate tutorial. At end of this tutorial, you will have the exact same result but with entities configured using Fluent NHibernate instead of an XML configuration file.

1. Open you the Solution PocoLib.

2. Add a reference to FluentNHibernate in the PocoLibTests

3. Add a new class named CustomerMap.cs to the PocoLibTests project. The source code for CustomerMap.cs is in the left column in the table below. The code speaks for itself; it's almost identical in structure to the XML configuration file.

CustomerMap.cs Customer.hbm.xml

using FluentNHibernate.Mapping;
using PocoLib;

namespace PocoLibTests
  public class CustomerMap : ClassMap<Customer>
    public CustomerMap()

      Id(cust => cust.ID, "CustomerID");

      Map(cust => cust.FirstName);
      Map(cust => cust.LastName);
      Map(cust => cust.BirthDate);

      Component<Address>(cust => cust.Address,
        component =>
          component.Map(address => address.Street);
          component.Map(address => address.State);
          component.Map(address => address.Country);
          component.Map(address => address.ZipCode);

<class name="Customer"

  <id name="ID" column="CustomerID">
    <generator class="native"/>

  <property name="FirstName"/>
  <property name="LastName"/>
  <property name="BirthDate"/>

  <component name="Address">

    <property name="Street"/>
    <property name="State"/>
    <property name="Country"/>
     <property name="ZipCode"/>


4. Now, open the test class. We must change the Setup method and replace the line that loads the the configuration from Customer.hbm.xml to load it using Fluent Nhibernate.

public void Setup()
    Configuration configuration = new Configuration();


        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerCRUDTests>())

    _factory = configuration.BuildSessionFactory();

5. Delete the Customer.hbm.xml file from the PocoLib project and from the /debug/bin/ folder of the PocoLibTests project.

6. You can now run the tests tests.

That's it for this quick Fluent NHibernate tutorial.