Most of the time I do not have to touch Fluent NHibernate conventions I have created some time ago. But from time to time I find in mappings some common scenario which is a good candidate to become a convention. This time I found that every time I am mapping a property of enumeration type I have to specify its length manually.
Because I hate redundant work I have defined a Fluent NHibernate convention presented below.
using System;
using System.Linq;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;
namespace ExampleConventions
{
public class EnumColumnLengthConvention
: IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType.IsEnum)
.Expect(x => x.Length == 0);
}
public void Apply(IPropertyInstance instance)
{
var names = Enum.GetNames(instance.Property.PropertyType);
instance.Length(names.Max(name => name.Length));
}
}
}
The convention is really simple. Its whole logic can be found in Apply method and I think it is self explanatory so there is nothing to describe here.
[...] This post was mentioned on Twitter by Marcin Obel, Pawel Lesnikowski. Pawel Lesnikowski said: RT @marcinobel: Blogged: Fluent NHibernate conventions II – example for enumerations http://bit.ly/d7MSiB [...]