开发者

NHibernate property access strategy, How to set it up so that field.camelcase-underscore is preferred but autoproperty is fall back

开发者 https://www.devze.com 2022-12-19 15:07 出处:网络
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 propert开发者_JAVA技巧y.

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 propert开发者_JAVA技巧y.

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


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消