[英]Automapper use destination properties and map single property
我想使用自動映射器在2個列表之間進行映射。 一個列表包含一個代碼和一個字符串,另一個包含代碼和其他字段。 我想使用目標對象上所有現有的值/屬性,除了一個。 automapper有可能嗎? 我不想使用UseDestinationValue()指定所有屬性。 嘗試了以下操作,但是它沒有返回更新了一個屬性的目標列表,而是返回了一個僅包含匹配項的新列表(在兩個列表中),並且所有字段均為空:
public static IMappingExpression<TSource, TDest> UseAllDestinationValues<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.UseDestinationValue());
return expression;
}
Mapper.CreateMap<Perm, PermViewModel>()
.UseAllDestinationValues()
.ForMember(dest => dest.CanEdit, opt => opt.MapFrom(s => s.editable));
var items = Mapper.Map<List<Perm>, List<PermViewModel>>(list, model.Items.Items);
我必須使用從一個應用程序到另一個應用程序的可為空的double來做類似的事情。 您可以設置一個類型轉換器。 沒有您的特定班級,我無法確切地說出該如何做,但這是我的示例。
Mapper.CreateMap<double?, double>().ConvertUsing<NullableDoubleConverter>();
private class NullableDoubleConverter : TypeConverter<double?, double>
{
protected override double ConvertCore(double? source)
{
if (source == null)
return Constants.NullDouble;
else
return (double)source;
}
}
您顯然可以使用類似的方法對此進行調整。
Mapper.CreateMap<Perm, PermViewModel>().ConvertUsing<PermConverter>();
private class PermConverter : TypeConverter<Perm, PermViewModel>
{
protected override PermViewModel ConvertCore(Perm source)
{
return new PermViewModel()
{
//Set your parameters here.
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.