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()
    {
      Not.LazyLoad();

      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"
        lazy="false">

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

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

  <component name="Address">


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

</class>

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.

[SetUp]
public void Setup()
{
    Configuration configuration = new Configuration();
    configuration.Configure("PocoLib.cfg.xml");

    configuration.AddXmlFile("Customer.hbm.xml");

    Fluently.Configure(configuration)
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerCRUDTests>())
        .BuildConfiguration();

    _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.

2 comments: