On Fluent NHibernate

time to read 3 min | 566 words

There has been some noise lately about Fluent NHibernte. This gives you a fluent interface to configure NHibernate mapping. I don't really see the point, frankly. Fluent NHibernate, at least in its current stage, requires a mapping class per entity. At this point, I might as well use the XML again.

In general, anything that requires me to touch two places to make one change is suspect. That is part of the reason that I like ActiveRecord, the change is highly localized.

NHibernate's XML serve a very different purpose, it is explicitly designed to separate the persistence concern from the entity, so it has to be external. This is annoying, to say the least.

What would be the best of both worlds, however, would be something like this:

public class MyMappingGenerator : MappingGenerator
{
    // another approach would be IEnumerable<Assembly> GetEntitiesAssemblies()
    public override IEnumerable<Type> GetEntityTypes()
    {
        foreach(Type maybeEntity in Assembly.Load("My.Model").GetTypes())
        {
            if(maybeEntity.Namespace == "My.Model.Entities")
                continue;
            yield return maybeEntity;
        }
    }
   
    public override IEnumerable<Type> GetHierarcyRoots()
    {
        yield return typeof(Party);
        yield return typeof(Animal);
    }
   
    public override InheritenceMode GetDefaultInheritenceMode()
    {
        return InheritenceMode.Discriminator;
    }
   
    public override IdentityStrategy GetIdentityStrategy()
    {
        return new HiLo("Id");
    }
   
    public override IEnumerable<MappingStrategy> GetMappingStrategies()
    {
        yield return new MapSimpleProperties();
        yield return new MapManyToOnePropertiesIn(typeof(Party).Assembly);
        yield return new MapManyToManyAssociationsBetween(new Hashtable{
            {typeof(Customer), typeof(Party)},
            {typeof(Party), typeof(Customer)}
        });
        yield return new MapOneToMany().AsSet();
    }
}

This allow you to define the convention, and let the tool deal with it. If it reminds you of Binsor you are correct.

Chad hints that this is either possible to do right now, or will soon be possible, using Fluent NHibernate. And at that point, I would be very interested.