自动映射器从源嵌套集合映射到另一个集合

本文关键字:集合 映射 另一个 嵌套 | 更新日期: 2023-09-27 18:34:42

>编辑:标题不正确,我正在尝试从源列表映射到嵌套模型的源列表。

我在尝试将列表映射到嵌套模型中列出的另一个列表时遇到问题。有点不平坦。问题是我不知道如何进行映射。

这是我在映射尝试失败后的设置:

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

其中 Item 和 ItemModel 已在它们之间定义了映射

我不能这样做...

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

错误:

表达式 'd => d.DestinationNestedViewModel.NestedList' 必须解析为顶级成员。参数名称:lambda表达式

然后我尝试了这样的事情:

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

那里的问题是 NestedList = t.SourceList。它们分别包含不同的元素,ItemModelItem。因此,需要对它们进行映射。

我该如何映射?

自动映射器从源嵌套集合映射到另一个集合

我想你想要这样的东西:

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

然后,您所要做的就是在SourceDestination之间调用Mapper.Map

Mapper.Map<SourceModel, DestinationModel>(source);
相关文章: