[英]automapper: generate condition by naming convention
能否請你幫我一下。 找不到如何更新自動映射器約定或任何其他配置以實現跟蹤的方法。
假設我有一個這樣的課程:
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我想使用一些常規條件。
提前致謝!
謝謝@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());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.