Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
getit Avatar asked May 18 '12 22:05

getit


People also ask

Does AutoMapper map nested objects?

With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.

Can AutoMapper map collections?

AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

Is AutoMapper bidirectional?

The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.


1 Answers

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);
like image 191
Andrew Whitaker Avatar answered Sep 17 '22 13:09

Andrew Whitaker