12

編集: タイトルが正しくありません。ソース リストからネストされたモデルのソース リストにマップしようとしています。

リストをネストされたモデルにリストされている別のリストにマップしようとすると問題が発生します。一種の非平坦化。問題は、マッピングの方法がわからないことです。

失敗したマッピングの試みに続く私のセットアップは次のとおりです。

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という異なる要素が含まれています。したがって、それらをマッピングする必要があります。

これをどのようにマッピングしますか?

4

1 に答える 1

20

私はあなたがこのようなものが欲しいと思います:

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.Map次に、 との間Sourceで呼び出すだけですDestination

Mapper.Map<SourceModel, DestinationModel>(source);
于 2012-05-19T12:40:02.090 に答える