[英]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.