Using automapper to apply a filter to a collection

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 17:04:19

问题


I have a domain model that contains a collection and I want to use AutoMapper to map the parent and children to the view model but I don't want children that have been "soft" deleted to be taken across. For instance:

public class Customer {
   public EntitySet<Order> {get;set;}
}
public class Order {
   public DateTime? DeletedDate {get;set;}
}

my AutoMapper definition would be

Mapper.CreateMap<Customer, CustomerViewModel>();
Mapper.CreateMap<Order, OrderViewModel>();

and I don't want Orders to be in the view model that have a value for DeletedDate.

Is that possible in AutoMapper? Many thanks in advance,

Steve.


回答1:


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".




回答2:


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.



来源:https://stackoverflow.com/questions/6226419/using-automapper-to-apply-a-filter-to-a-collection

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