我想设置访问策略,以便在存在field.camelcase-underscore属性支持时使用其他使用自动属性。
这是默认行为(因为自动道具基本上有后退字段)?或者我如何强制执行此操作?
答案 0 :(得分:4)
默认情况下使用属性的setter,因此如果您有一个支持字段,则需要将访问权限指定为camelcase下划线字段(或您使用的任何命名约定)。
可能有一种更简单的方法可以实现这一点,但您可以使用Fluent NHibernate的约定来强制执行使用支持字段(如果可用)的这种行为,否则使用setter。应用约定时,您可以反映实体类型以检查是否存在相应的camelcase下划线字段。如果找到了支持字段,则修改映射以使用camelcase underscore作为访问权限。
以下是使用IPropertyConvention的示例。 (您可能希望在一对多约定等中进行相同类型的检查):
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;
}
}