[英]AutoMapper: Limit number of rows in nested model
I have a viewModel with lots of properties and a lot of collections of other viewModels 我有一个带很多属性的viewModel和许多其他viewModels的集合
public ICollection<ListView> Elements { get; set; }
Can I specify somewhere that AutoMapper only takes the first 10 elements of this collection? 我可以在某个地方指定AutoMapper仅采用此集合的前10个元素吗?
You could do a resolve using in your map. 您可以在地图中使用来解决问题。 This would give you an opportunity to put in your own expression like so: 这将使您有机会像这样输入自己的表达式:
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;
}));
}
Resolve using in your mapping configuration allows you to specify how you want to map one thing to another. 通过在映射配置中使用“解决”,您可以指定如何将一件事映射到另一件事。
More info and examples can be found here: https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers 更多信息和示例可以在这里找到: 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
}
}
You could also use custom resolvers to do this: https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers#customizing-the-source-value-supplied-to-the-resolver 您还可以使用自定义解析器执行此操作: https : //github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers#customizing-the-source-value-supplied-to-the-resolver
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.