c a n d l a n d . n e t

Changing The FluentNHibernate Id Conventions

Dusty Candland | |

FluentNhibernate provides a bunch of Convention interfaces and base classes to override the default conventions. In this case our database naming requires Id columns to include the table name like ProductId for the Products table. Also, we’re using the HiLo algorithm. This can be done with a simple class the implements IIdConvention.

public class FullIdNameConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(instance.EntityType.Name + "Id");
        instance.GeneratedBy.HiLo("100");
    }
}

The convention also required referenced id to be named as Id where the default is _id. This can be changed with the follow two classes.

public class ManyToManyIdNameConvention : IHasManyToManyConvention
{
    public void Apply(IManyToManyCollectionInstance instance)
    {
        instance.Key.Column(instance.EntityType.Name + "Id");
        instance.Relationship.Column(instance.Relationship.StringIdentifierForModel + "Id");
    }
}

public class ReferenceIdNameConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(instance.Name + "Id");
    }
}

Some cases may require other interface implementations.

Lastly, FluentNhibernate needs to know about these conventions which can be on the AutoPersistenceModel class passed to the NHibernate configuration. This is done in an implementation of IConfigurationBuilder passed to the Castle NHibernate Facility.

var model = new AutoPersistenceModel()
    .AddEntityAssembly(typeof(Product).Assembly)
    .Where(t => t.Namespace.StartsWith(typeof(Product).Namespace))
    .Conventions.AddFromAssemblyOf<FullIdNameConvention>()
    .UseOverridesFromAssemblyOf<ProductMapping>()
    ;

configuration.AddAutoMappings(model);

More info can be found on the FluentNHibernate wiki.

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: