I'm trying to map two collections by using EF's navigation property.
Collection.Items
is a List<Item>
CollectionDTO
has a navigation property to a cross-join table called CollectionItem
, which has another navigation property to Item
.
I want each CollectionDTO.CollectionItem.Item
to map to Collection.Item
.
I have tried this but I can't figure it out.
Can someone help?
var mapperConfig = new MapperConfiguration(cfg =>
{
// CreateMap<source, destination>()
cfg.CreateMap<Collection, CollectionDTO>()
.ForMember(dest => dest.Items,
opts => opts.MapFrom(src =>
src.CollectionItems.Where(x => x.CollectionId == src.Id).ToList().ForEach(ci => ci.Item)));
});
You can use Select
extension method like this:
// CreateMap<source, destination>()
cfg.CreateMap<Collection, CollectionDTO>()
.ForMember(dest => dest.Items,
opts => opts.MapFrom(src =>
src.CollectionItems.Select(ci=>ci.Item).ToList()));
If Item
navigation property is a collection, then use SelectMany
extension method:
// CreateMap<source, destination>()
cfg.CreateMap<Collection, CollectionDTO>()
.ForMember(dest => dest.Items,
opts => opts.MapFrom(src =>
src.CollectionItems.SelectMany(ci=>ci.Item).ToList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With