Как создать функцию AutoMap для FluentNHibernate на основе атрибутов? - PullRequest
0 голосов
/ 05 ноября 2011

Я хочу использовать механизм карты, основанный на маркировке атрибутов свойств, например:

[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 Ответ

1 голос
/ 07 ноября 2011
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));
}
...