开发者

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

开发者 https://www.devze.com 2023-01-12 12:52 出处:网络
I\'m looking for a FluentNH (Flu开发者_StackOverflow社区ent NHibernate) convention or configuration that ignores all properties that have no setter:

I'm looking for a FluentNH (Flu开发者_StackOverflow社区ent 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;}} //<-------
}


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


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.


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;
}


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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消