Using automapper to apply a filter to a collection

stevie_c picture stevie_c · Jun 3, 2011 · Viewed 7.2k times · Source

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.

Answer

achekh picture achekh · Jun 20, 2011

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