Nullable properties with Fluent nhibernate automapping

If you are using fluent nhibernate then mapping nullable columns is easy – just call the .Nullable() method for the property mapping:

   Map(x => x.Name).Nullable();

Unfortunately, my mind has been poisoned by Rails and its convention over configuration value, so I can't ignore automapping. Automapping uses configurable sensible defaults to do the mapping for you. The out-of-the-box defaults make every property nullable, which does not suit my style, so I wrote an IPropertyConvention to override this behaviour and make everything not-nullable:

public class NotNullPropertyConvention : IPropertyConvention 
    { 
        public bool Accept(IProperty target) 
        { 
            return true; 
        } 

        public void Apply(IProperty target) 
        { 
            target.Not.Nullable(); 
        } 
    }

My plan was to use fluent nhibernate’s Nullable() method to override this default for properties that I actually wanted to be nullable. But it doesn’t work. The automapping convention overrides the fluent nhibernate setting. To get things to work the required way I had to modify the NotNullPropertyConvention to:

public class NotNullPropertyConvention : IPropertyConvention
    {
        public bool Accept(IProperty target)
        {
            return !IsNullableProperty(target);
        }

        public void Apply(IProperty target)
        {
            target.Not.Nullable();
        }

        private bool IsNullableProperty(IProperty target)
        {
            var type = target.PropertyType;
            return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof (Nullable<>));
        }
    }

This updated convention is only applied to properties that are not nullable. Perfect!


Comments are closed