繁体   English   中英

AutoMapper从源嵌套集合映射到另一个集合

[英]AutoMapper map from source nested collection to another collection

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

我在尝试将列表映射到嵌套模型中列出的另一个列表时遇到问题。 种类和不平整的种类。 问题是我不知道如何做映射。

这是我的设置跟随我失败的映射尝试:

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'必须解析为顶级成员。参数名称:lambdaExpression

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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