简体   繁体   中英

AutoMapper map from source nested collection to another collection

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM