Monday, June 21, 2010

Fluent NHibernate configuration (Ms Sql Server 2005 & Mysql)..


NHibernate is popular in Open-source community, fully featured, mature ORM but the way to config mappings in XML files (.hbm.xml files) is not comfort.
I would prefer to write mappings in strongly typed C# code and enjoy from easy refactoring, improved readability and more concise code.

Fluent NHibernate resolves this issue and provides alternative to NHibernate's standard XML mapping files - fluent, XML-less, compile safe.

Samples of mappings:
public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        WithTable("Customers");
 
        Id(x => x.Id, "CustomerId");
        Map(x => x.Firstname);
        Map(x => x.Lastname);
        Map(x => x.Email, "EmailAddress");
    }
}
 
//For sql server2005
Fluently.Configure()
  .Database(MsSqlConfiguration.MsSql2005
    .ConnectionString(c => c
      .FromAppSetting("connectionString"))
    .Cache(c => c
      .UseQueryCache()
      .ProviderClass<HashtableCacheProvider>())
    .ShowSql())
  .Mappings(m => m
    .FluentMappings.AddFromAssemblyOf<Customer>())
  .BuildSessionFactory();
//For Mysql
Fluently.Configure()
.Database(MySqlConfiguration.Standard
.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString")))     .Mappings(m => m.FluentMappings.AddFromAssemblyOf())     .BuildSessionFactory()) 

Always looking forward to maintain whole schema of a database is really challenging..

1 comment:

  1. Im a newbie in Fluent Nhibernate and Asp.net., can you please give me a sample Asp.net project using the Fluent Nhibernate Automapping., im using MySql. thank you very much pandiya

    ReplyDelete