Ian mentions the use of a configuration file for configuring NHibernate in his excellent post on getting started with NHibernate. I quickly wanted to mention the use of Fluent NHibernate for configuring NHibernate, which allows you to avoid all the XML.
Without the need for any of the NHibernate XML one can configure NHibernate similar to Ian with just a few lines of code:
class Program
{
private static ISessionFactory sessionFactory = null;
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var cfg = new Configuration();
var configuration = MsSqlConfiguration.MsSql2000.ShowSql().ConnectionString.Is(
“Data Source=.;Initial Catalog=Temp;Integrated Security=True”).ConfigureProperties(cfg);
sessionFactory = configuration.BuildSessionFactory();
}
}
This may or may not be attractive to you based on your needs and preferences, but it certainly makes it a really nice option if you want to avoid the XML.
What gets even more exciting is when you want to map the classes. Personally I hate using XML for it, which makes it even nicer to add the class mappings like:
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
WithTable(“Customers”);
Id(x => x.Id);
Map(x => x.Firstname);
Map(x => x.Lastname);
Map(x => x.Email);
}
}
In that case the columns and properties map 1:1, but if you had some difference you can do:
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”);
}
}
I can add the entity mappings to the configuration with an additional line of code
configuration.AddMappingsFromAssembly(typeof(Customer).Assembly);
so now the code above becomes:
class Program
{
private static ISessionFactory sessionFactory = null;
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var cfg = new Configuration();
var configuration = MsSqlConfiguration.MsSql2000.ShowSql().ConnectionString.Is(
“Data Source=.;Initial Catalog=Temp;Integrated Security=True”).ConfigureProperties(cfg);
configuration.AddMappingsFromAssembly(typeof(Customer).Assembly);
sessionFactory = configuration.BuildSessionFactory();
}
}
I really like the simplicity of all this. It makes NHibernate much more approachable in my opinion.
You can check out the Fluent NHibernate Project here.
Check out Sharp Architecture for some of the Fluent NHibernate in action.
Recent Posts:
Sounds great, Ian!
I look forward to your series on NHibernate.
Thanks David. I’ll link back to you when I cover entities too. I will cover Castle Active Record but it would be great if you wanted to supplement any of my posts with fluent NHibernate observations.
Wow it’s almost like CodeBetter teamwork