How can I create a Fluent NHibernate Convention that ignores properties that don't have setters

孤街浪徒 提交于 2019-12-23 15:24:06

问题


I'm looking for a FluentNH (Fluent NHibernate) convention or configuration that ignores all properties that have no setter:

It would still map these:

public class foo{
  public virtual int bar {get; private set;}
}

And omit these:

public class foo{
  public virtual int fizz{get;private set;}
  public virtual int bar{get {return fizz;}} //<-------
}

回答1:


You should use a custom mapping configuration

public class DefaultMappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        return member.CanWrite;
    }
}

Usage :

var nhConfiguration = new Configuration().Configure();
var mappingConfiguration = new DefaultMappingConfiguration();

var.fluentConfiguration = Fluently.Configure(nhConfiguration );
    .Mappings(m => m.AutoMappings.Add(
        AutoMap.AssemblyOf<MappedType>(mappingConfiguration)
    ));

var sessionFactory = this.fluentConfiguration.BuildSessionFactory();

However, private setters won't get mapped. You should get them as protected




回答2:


Use this:

public class DefaultMappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.IsProperty && !member.CanWrite)
        {
            return false;
        }

        return base.ShouldMap(member);
    }
}

That should handle the case of no setter and private setter.




回答3:


I know this is old question but code below do well with private setters.

public override bool ShouldMap(Member member)
{
    var prop = member.DeclaringType.GetProperty(member.Name);
    bool isPropertyToMap = 
        prop != null &&
        prop.GetSetMethod(true) != null &&
        member.IsProperty;

    return
        base.ShouldMap(member) && isPropertyToMap;
}



回答4:


Another way is to use an attribute.

public class MyEntity
{
    [NotMapped]
    public bool A => true;
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Member member)
    {
        if (member.MemberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0)
        {
            return false;
        }
        return base.ShouldMap(member);
    }
}


来源:https://stackoverflow.com/questions/3547023/how-can-i-create-a-fluent-nhibernate-convention-that-ignores-properties-that-don

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!