本文介绍了如何忽视的利用代码"映射属性映射;会议及QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法避免使用映射通过编码规范与NHibernate 3.2被映射的属性?默认情况下,所有属性都映射
Is there any way to avoid a property from being mapped with NHibernate 3.2 using mapping by code conventions? By default, all properties are mapped.
推荐答案
有两种选择,据我所知:
There are two options as far as I know:
1)扩展ConventionModelMapper和SimpleModelInspector延长IsPersistentProperty,使其满足您的需要。
1)Extend ConventionModelMapper and SimpleModelInspector to extend IsPersistentProperty such that it meets your need.
2)使用IsPersistentProperty如下:
2)Use IsPersistentProperty as follows:
...
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;
}
这篇关于如何忽视的利用代码"映射属性映射;会议及QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!