我有一个viewModel,它有很多属性和很多其他viewModel
的集合public ICollection<ListView> Elements { get; set; }
我可以指定AutoMapper只占用此集合的前10个元素吗?
答案 0 :(得分:1)
您可以在地图中使用解决方案。这将使您有机会像这样输入自己的表达式:
YourClassConstructorOrWhatever(){
AutoMapper.Mapper.CreateMap<YourSourceObject, YourDestObject>()
.ForMember(dest => dest.Elements, opt => opt.ResolveUsing(src =>
{
var result = new List<YourMapObject>();
foreach (var element in src.Elements.Take(10))
{
result.Add(Mapper.Map<YourMapObject>(element));
}
return result;
}));
}
在映射配置中使用解析允许您指定将一个事物映射到另一个事物的方式。
可在此处找到更多信息和示例: https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers
Mapper.Initialize(cfg => {
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total,
opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.SubTotal));
cfg.CreateMap<OtherSource, OtherDest>()
.ForMember(dest => dest.OtherTotal, opt => opt.ResolveUsing<CustomResolver, decimal>(src => src.OtherSubTotal));
});
public class CustomResolver : IMemberValueResolver<object, object, decimal, decimal> {
public decimal Resolve(object source, object destination, decimal sourceMember, decimal destinationMember, ResolutionContext context) {
// your mapper logic here
}
}
您也可以使用自定义解析器执行此操作: https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers#customizing-the-source-value-supplied-to-the-resolver