AutoMapper map from source nested collection to another collection

22,510

I think you want something like this:

Mapper.CreateMap<Item, ItemModel>();

/* Create a mapping from Source to Destination, but map the nested property from 
   the source itself */
Mapper.CreateMap<SourceModel, DestinationModel>()
    .ForMember(dest => dest.DestinationNestedViewModel, opt => opt.MapFrom(src => src));

/* Then also create a mapping from Source to DestinationNestedViewModel: */
Mapper.CreateMap<SourceModel, DestinationNestedViewModel>()
    .ForMember(dest => dest.NestedList, opt => opt.MapFrom(src => src.SourceList));

Then all you should have to do is call Mapper.Map between Source and Destination:

Mapper.Map<SourceModel, DestinationModel>(source);
Share:
22,510
getit
Author by

getit

Updated on July 09, 2022

Comments

  • getit
    getit almost 2 years

    EDIT: Title is incorrect, I am trying to map from a source list to a nested model's source list.

    I am having trouble trying to map a list to another listed in a nested model. Kind of and un-flatten of sorts. The problem is I don't know how to do the mappings.

    Here is my set up followed my failed attempts at mapping:

    public class DestinationModel
    {
        public DestinationNestedViewModel sestinationNestedViewModel { get; set; }
    }
    
    public class DestinationNestedViewModel
    {
        public List<ItemModel> NestedList { get; set; }
    }
    
    public class SourceModel
    {
        public List<Item> SourceList { get; set; }
    }
    

    Where Item and ItemModel already have a mapping defined between them

    I can't do it this way...

    Mapper.CreateMap<SourceModel, DestinationModel>()
    .ForMember(d => d.DestinationNestedViewModel.NestedList,
        opt => opt.MapFrom(src => src.SourceList))
    

    ERROR:

    Expression 'd => d.DestinationNestedViewModel.NestedList' must resolve to top-level member.Parameter name: lambdaExpression

    I then tried something like this:

    .ForMember(d => d.DestinationNestedViewModel, 
     o => o.MapFrom(t => new DestinationNestedViewModel { NestedList = t.SourceList }))
    

    The problem there is NestedList = t.SourceList. They each contain different elements, ItemModel and Item respectively. So, they need to be mapped.

    How do I map this?