Sunday, February 06, 2011

Defining Acceptance criteria for mapping conventions in NHibernate

Today I'm hosting a post from Leeran Yarhi, one of the developers in my team:
Hi guys,
I’m Leeran Yarhi, a developer in Yossi’s team.

Recently we had a problem while mapping one of our domain entities with Fluent NHibernate. We upgraded our app to use NHibernate 3 in conjunction with Fluent NHibernate 1.2. When we did that, some of our tests failed.

For example, let’s have a look at this entity:

public class User
{
   public virtual int Id { get; set; }
   public virtual string FirstName { get; set; }
   public virtual string LastName { get; set; }
   public virtual string FullName { get; private set; }
}

And it’s mapping:

public class UserMap : ClassMap<User>
{
  public UserMap()
  {
      Id(x => x.Id);
      Map(x => x.FirstName);
      Map(x => x.LastName);
      Map(x => x.FullName).Formula("first_name || ' ' || last_name");
  }
}

As you can see, User has a property named FullName, which is actually a concatenation of FirstName and LastName. Of course I don’t really want to map this property to our Database. This is why I’m defining it a Formula, so that my Users table won’t really have a column for FullName
All good, but the problem starts when I try to use this PropertyConvention :

public class PropertyUnderscoreConvention : IPropertyConvention
{
   public void Apply(IPropertyInstance instance)
   {
       instance.Column(Inflector.Underscore(instance.Property.Name));
   }
}

Read more: YsA.Net