Tags: , , , , | Categories: development Posted by pieterg on 3/15/2010 8:14 AM | Comments (10)

It’s difficult to break away from old traditions, but sometimes it pays to think a differently. NHibernate is an awesome example of what I am talking about. It gives a developer the flexibility of concentrating on writing code instead of having to synchronize the database with the data layer/code.

Currently, what I see happening quite often is the following.

  1. Specification document gets drawn up.
  2. Database is slapped together by the developer or DB “dude”.
  3. Developer starts working on the code, only to realize that a column is missing due to either poor planning or requirements changing, the developer spends time having to change/add a column/s and tracking down all the changes in the stored procedure and hopefully he/she has tracked all of them down, otherwise….

    15154

I have 2 words, Fluent NHibernate…

How to setup Fluent NHibernate

  1. Download Fluent NHibernate from http://fluentnhibernate.org/downloads
  2. Add references to the DLLs
  3. Create your first Entity
    public class Person
    {
    	public virtual int ID { get; private set; }
    	public virtual string Name { get; set; }
    	public virtual string Lastname { get; set; }
    }
    
    public class PersonMap : ClassMap<Person>
    {
    	public PersonMap()
    	{
    		Schema("dbo");
    		Table("Person");
    		Id(x => x.ID);
    		Map(x => x.Name);
    		Map(x => x.Lastname);
    	}
    }
  4. Setup Fluent NHibernate and this is where fluent really shines. No more having to deal with the pain of the XML configuration.
    public static class SessionFactory
    {
    	public static ISessionFactory CreateSessionFactory()
    	{
    		return Fluently.Configure()
    			.Database(MsSqlConfiguration.MsSql2005
    			.ConnectionString(
    				c => c.FromConnectionStringWithKey("AthenaConnectionString")))
    			.Mappings(
    				m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
    			.ExposeConfiguration(BuildSchema)
    			.BuildSessionFactory();
    	}
    
    	private static void BuildSchema(Configuration config)
    	{
    		new SchemaUpdate(config).Execute(true, true);
    	}
    }
    
  5. How to use Fluent NHibernate in a simple example
var sessionFactory = SessionFactory.CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
	using (var transaction = session.BeginTransaction())
	{
		Person person = new Person { Name = "Pieter", Lastname = "Germishuys" };
		session.SaveOrUpdate(person);
		transaction.Commit();
	}
}

3JDQDM2DSFR8