如何使用代码映射“约定”忽略属性的映射
本文关键字:映射 属性 约定 何使用 代码 | 更新日期: 2023-09-27 18:11:51
是否有任何方法可以避免使用NHibernate 3.2使用映射的代码约定来映射属性?默认情况下,所有属性都被映射。
2)作为复制&粘贴IsPersistentProperty默认实现的替代方案,它可以通过反射来重用:
var mapper = new ConventionModelMapper();
var field = mapper.ModelInspector.GetType()
.GetField( "isPersistentProperty", BindingFlags.NonPublic | BindingFlags.Instance );
var ispp = (Func<MemberInfo, bool, bool>)field.GetValue( mapper.ModelInspector );
mapper.IsPersistentProperty( ( mi, b ) => ispp( mi, b )
&& ( /*any conditions here*/ mi.Name != "SomeFiledName" ) );
条件可以移动到单独的方法或类中。基于表达式的强类型包装器可以在上面完成。
据我所知有两种选择:
1)扩展ConventionModelMapper和SimpleModelInspector来扩展IsPersistentProperty,以满足您的需要。
2)使用IsPersistentProperty如下:
...
mapper.IsPersistentProperty((memberInfo, declared) => IsPersistentProperty(mapper.ModelInspector, memberInfo, declared, "YourPropertyName"));
...
public static bool IsPersistentProperty(IModelInspector modelInspector, MemberInfo member, bool declared, string propertyName)
{
return (declared ||(member is PropertyInfo) && !IsReadOnlyProperty(member)) && !member.Name.Equals(propertyName);
}
private static bool IsReadOnlyProperty(MemberInfo subject)
{
const BindingFlags defaultBinding = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var property = subject as PropertyInfo;
if (property == null)
{
return false;
}
if (CanReadCantWriteInsideType(property) || CanReadCantWriteInBaseType(property))
{
return !PropertyToField.DefaultStrategies.Values.Any(s => subject.DeclaringType.GetField(s.GetFieldName(property.Name), defaultBinding) != null) || IsAutoproperty(property);
}
return false;
}
private static bool IsAutoproperty(PropertyInfo property)
{
return property.ReflectedType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.DeclaredOnly).Any(pi => pi.Name == string.Concat("<", property.Name, ">k__BackingField"));
}
private static bool CanReadCantWriteInsideType(PropertyInfo property)
{
return !property.CanWrite && property.CanRead && property.DeclaringType == property.ReflectedType;
}
private static bool CanReadCantWriteInBaseType(PropertyInfo property)
{
if (property.DeclaringType == property.ReflectedType)
{
return false;
}
var rfprop = property.DeclaringType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
| BindingFlags.DeclaredOnly).SingleOrDefault(pi => pi.Name == property.Name);
return rfprop != null && !rfprop.CanWrite && rfprop.CanRead;
}
Duplicate: Ignore column using mapping by code in hibernate
你可以使用以下命令:
mapper.IsPersistentProperty((mi, declared) =>
{
if (mi.DeclaringType == typeof (YourType) && mi.Name == "PropertyNameToIgnore")
return false;
return true;
});