Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper with EF Navigation Properties

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)));

});
like image 763
duyn9uyen Avatar asked Oct 31 '22 01:10

duyn9uyen


1 Answers

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()));
like image 50
octavioccl Avatar answered Nov 11 '22 15:11

octavioccl