假设我有这样的课程:
public class A
{
public bool PropertyUpdated {get;set;}
public int PropertyValue {get;set;}
}
和
public class B
{
public int PropertyValue {get;set;}
}
我可以以某种方式自动生成以下地图(通过命名对流等)
CreateMap<A,B>()
.ForMember(b => b.PropertyValue, mm =>
{
mm.Condition(a => a.PropertyUpdated);
mm.MapFrom(a => a.PropertyValue);
});
我有很多这样的属性,不想自己写这样的规则。只是想知道是否有办法告诉automapper我想使用一些条件。
提前致谢!
答案 0 :(得分:0)
感谢@Lucian,它就是诀窍。
ForAllPropertyMaps(pm => !pm.SourceMember.Name.EndsWith("Updated"), (pm, ce) =>
{
var sourceType = pm.TypeMap.SourceType;
var conditionPropertyName = $"{pm.SourceMember.Name}Specified";
var property = sourceType.GetProperty(conditionPropertyName, BindingFlags.Instance | BindingFlags.Public);
if (property == null) return;
var conditionParameter = Expression.Parameter(typeof(object));
var parameterConvertion = Expression.Convert(conditionParameter, sourceType);
var getPropertyValue = Expression.Property(parameterConvertion, conditionPropertyName);
var lambda = Expression.Lambda<Func<object, bool>>(getPropertyValue, conditionParameter);
ce.Condition(lambda.Compile());
});