问题
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