簡體   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