[英]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 其中Item和ItemModel已经在它们之间定义了映射
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 表达式'd => d.DestinationNestedViewModel.NestedList'必须解析为顶级成员。参数名称: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 . 那里的问题是NestedList = t.SourceList 。 They each contain different elements, ItemModel and Item respectively.
它们分别包含不同的元素, ItemModel和Item 。 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
: 那么你所要做的就是在
Source
和Destination
之间调用Mapper.Map
:
Mapper.Map<SourceModel, DestinationModel>(source);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.