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?
With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.
AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.
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);
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