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

时间:2012-05-18 22:44:10

标签: c# model-view-controller nested viewmodel automapper

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

我无法尝试将列表映射到嵌套模型中列出的其他列表。种类和不平整的种类。问题是我不知道如何做映射。

以下是我在设置映射失败后的设置:

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 =&gt; d.DestinationNestedViewModel.NestedList'必须解析为顶级成员。参数名称:lambdaExpression

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

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

存在的问题      NestedList = t.SourceList 。 它们分别包含不同的元素, ItemModel 。所以,他们需要被映射。

如何映射?

1 个答案:

答案 0 :(得分:13)

我想你想要这样的东西:

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

然后您应该做的就是在Mapper.MapSource之间致电Destination

Mapper.Map<SourceModel, DestinationModel>(source);