views:

225

answers:

1

I want to set up the access strategy so that if a field.camelcase-underscore property backing is present then use that else use the automatic property.

is this the default behavior (since auto props have back fields essentially)? or how to I enforce this?

+1  A: 

The default is to use the setter of the property, so you need to specify access as camelcase underscore field (or whatever naming convention you use) if you have a backing field.

There might be a simpler way to achieve this, but you can use Fluent NHibernate's conventions to enforce this behaviour of using backing fields if available, and setters otherwise. When the convention is applied you can reflect over the entity type to check if there is a corresponding camelcase underscore field or not. If a backing field is found, you modify the mapping to use camelcase underscore as access.

Here is an example using IPropertyConvention. (You might want to do the same kind of check in a one-to-many convention etc as well):

public class PropertyAccessConvention : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        Type entityType = instance.EntityType;
        string camelCaseUnderscoreName = 
            ConvertToCamelCaseUnderscore(instance.Name);

        bool hasBackingField = HasField(entityType, camelCaseUnderscoreName);

        // Default is to use property setter, so only modify mapping
        // if there is a backing field

        if (hasBackingField)
            instance.Access.CamelCaseField(CamelCasePrefix.Underscore);
    }

    private static string ConvertToCamelCaseUnderscore(string propertyName)
    {
        return "_" +
            propertyName[0].ToString().ToLower() +
            propertyName.Substring(1);
    }

    private bool HasField(Type type, string fieldName)
    {
        FieldInfo backingField = type.GetField(
            fieldName, 
            BindingFlags.NonPublic | BindingFlags.Instance);

        return backingField != null;
    }
}
Erik Öjebo