如何根据属性为FluentNHibernate创建AutoMap功能?

时间:2011-11-05 00:38:47

标签: linq fluent-nhibernate nhibernate-mapping

我想使用基于属性属性标记的map机制,如下所示:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class DomainSignatureAttribute : Attribute { }

public class SomeThing {
    [DomainSignature]
    public virtual string SomePropertyForMapping {get;set;}
    [DomainSignature]
    public virtual int OtherPropertyForMapping {get;set;}

    public virtual string OtherPropertyWithoutMapping {get;}
}

所以在ClassMap的孩子们中我想实现这个方法,它映射所有属性,用DomainSignatureAttribute属性标记:

protected void MapPropertiesWithStandartType()
{
    foreach (PropertyInfo property in typeof(T).GetProperties())
    {
        if (property != null)
        {
            object[] domainAttrs = property.GetCustomAttributes(typeof (DomainSignatureAttribute), true);

            if (domainAttrs.Length > 0)
                Map(x => property.GetValue(x, null));
        }
    }
}

但Linq存在一个小问题。当FluentNHibernate构建映射(Cfg.BuildSessionFactory())时,它会打破

  

尝试在添加后添加属性'GetValue'。

异常。当我不准备时,我需要将Linq表达式x => property.GetValue(x, null)重建为正确的形式。

请不要建议使用AutoMap功能,也不建议使用手动映射。

1 个答案:

答案 0 :(得分:1)

var domainproperties = typeof(T).GetProperties()
    .Where(prop => prop.GetCustomAttributes(typeof (DomainSignatureAttribute), true).Length > 0);

foreach (var property in domainproperties)
{
    Map(Reveal.Member<T>(property.Name));
}