Using automapper to apply a filter to a collection

徘徊边缘 提交于 2019-12-04 22:43:38

I came across similar issue and finally the approach similar to the one below worked for me:

Mapper.CreateMap<Customer, CustomerViewModel>()
    .ForMember(dest => dest.Orders, 
        opt => opt.MapFrom(src => src.Orders.Where(o => !o.DeletedDate.HasValue)));

This assumes your Customer entity and CustomerViewModel dto have collections named "Orders".

ataddeini

This sounds like it would be a good fit for a custom ValueResolver. It will allow you to do your logic checks in an isolated fashion. I don't have Visual Studio in front of me right now, but I can add some sample code later if you'd like.

EDIT: After tinkering with this I don't think a ValueResolver is the way to go. I was able to get it to work by using the following conditional configuration for the Order mapping:

Mapper.CreateMap<Order, OrderViewModel>()
   .ForAllMembers(opt => opt.Condition(src => !src.DeletedDate.HasValue));

The only thing with this is that theOrderViewModel will still come over but it will be null. In other words if you had 3 orders, and one had a deletion date, then the number of orders you will have in your view model will still be 3, but the deleted value will be null. I'm guessing it would be best to just have 2, but I'm not seeing a clear way to do that right now.

Here's a post with a response from the author of AutoMapper that talks about a Skip method, but I wasn't able to see that feature in the latest release that I'm using.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!