我想设置访问策略,以便如果存在 field.camelcase-underscore 属性支持,则使用该属性,否则使用自动属性。
这是默认行为(因为自动 Prop 本质上有后字段)?或者我如何强制执行此操作?
最佳答案
默认情况是使用属性的 setter ,因此如果您有支持字段,则需要将访问指定为驼峰式下划线字段(或您使用的任何命名约定)。
可能有一种更简单的方法来实现此目的,但您可以使用 Fluent NHibernate 的约定来强制使用支持字段(如果可用)的行为,否则使用 setter 。应用约定时,您可以反射(reflect)实体类型以检查是否存在相应的驼峰式下划线字段。如果找到支持字段,则修改映射以使用驼峰式下划线作为访问权限。
这是一个使用 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;
}
}
关于NHibernate 属性访问策略,如何设置以便首选 field.camelcase-underscore 但 autoproperty 会回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193514/