加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:33:55 所属栏目:百科 来源:网络整理
导读:编辑:标题不正确,我试图从源列表映射到嵌套模型的源列表. 我在尝试将列表映射到嵌套模型中列出的另一个列表时遇到问题.种类和不平整的种类.问题是我不知道如何做映射. 这是我的设置跟随我失败的映射尝试: public class DestinationModel{ public Destinati
编辑:标题不正确,我试图从源列表映射到嵌套模型的源列表.

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

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

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.
它们分别包含不同的元素,ItemModel和Item.所以,他们需要被映射.

我该如何映射?

解决方法

我想你想要这样的东西:
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));

那么你所要做的就是在Source和Destination之间调用Mapper.Map:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读