0

我花了几天时间来了解 Fluent NHibernate 自动映射工作模型。这很好,但我不断检测到我的模式中缺少的新细节。现在我想为我的类添加额外的属性,但没有将它们映射到数据库。一个典型的情况是当我需要具有内部逻辑的额外属性时。
所以我阅读了示例并扫描了 StackOverflow,发现这不是要添加的另一个约定,而是继承 DefaultAutomappingConfiguration 并覆盖 ShouldMap 方法的问题。
好吧,没问题,一分钟后我有这样的事情:

public class CustomAutomappingConfiguration : DefaultAutomappingConfiguration
{

    public override bool ShouldMap(Member member)
    {
        var explicitSkip = member.PropertyType.GetCustomAttributes(typeof(SkipMap), false).Length > 0;
        if ((member.IsProperty && !member.CanWrite) || explicitSkip)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}


/// <summary>
/// Don't map this property to database.
/// </summary>
public class SkipMap : Attribute
{
}


public class DemoClass
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual MyBitwiseEnum Status { get; set; }

    public virtual bool IsValid
    {
        get
        {
            return (int)Status > 3;
        }
    }

    [SkipMap]
    public virtual bool IsBad
    {
        get
        {
            return MyBitwiseEnum.HasFlag(MyBitwiseEnum.Bad);
        }
        set
        {
            MyEnum = value ? MyBitwiseEnum | MyBitwiseEnum.Bad : MyBitwiseEnum ^ MyBitwiseEnum.Bad;
        }
    }
}

我知道我的演示课有点愚蠢,但它会说明我的观点。
这个想法是我想手动决定将哪些属性映射到数据库。

readonly 属性工作正常,因为 ShouldMap 方法将查找 property.CanWrite。但是不会检测到肯定设置的自定义属性。这是为什么!?
在约定方法中,我经常使用相同的方法,并且效果很好。为什么属性无法在此处检测到定义的属性,而在约定设置中显然可以。有解决方法吗?

4

2 回答 2

2

您是否已将新的 automapconvention 添加到 Automap?

AutoMap.AssemblyOf<>(new CustomAutomappingConfiguration())

更新:您从布尔类而不是属性获取 skip 属性

member.PropertyType.GetCustomAttributes(typeof(SkipMap), false)

应该

member.MemberInfo.GetCustomAttributes(typeof(SkipMap), false)
于 2012-04-19T08:03:36.147 回答
0

为了确保自定义属性适用于属性,请尝试添加[AttributeUsage(AttributeTargets.Property)]到您的SkipMap类中。

另一种可能性是属性名称与适用于不同目标的另一个属性发生冲突。尝试将类重命名为类似的MyVerySpecialSkipMap名称并重新测试以验证您没有属性冲突。至少,编写一些简单的反射代码来测试SkipMap应用程序上下文之外的属性,以确保可以找到它。

于 2012-03-29T14:12:50.043 回答