【问题标题】:Automapper - Does it map lists of objects?Automapper - 它是否映射对象列表?
【发布时间】:2011-05-15 16:03:14
【问题描述】:

我有以下 Automapper 定义:

Mapper.CreateMap<IB.BusinessComponents.Data.LocationMaster, IB.Entites.Master.Location>();
Mapper.CreateMap<IB.BusinessComponents.Data.LocationMaster, IB.Entites.Master.Location>()
    .ForMember(destination => destination.Id, source => source.MapFrom(item => item.LocationMasterID))
    .ForMember(destination => destination.ChildLocationList, source => source.Ignore());

当我映射单个对象时,这很好用。但我似乎无法传递对象列表。传入列表时是否需要不同的定义,还是不可能?

【问题讨论】:

  • 为什么你有两次相同的映射?你应该只定义一次(大概是第二个)
  • @BeRecursive - 可能是因为我总共有 2 小时使用此工具的经验。
  • 好吧,只要您正确定义映射,我就应该使用开箱即用的列表。您是指上述类型的列表吗?您不需要为显式对象列表定义映射,只需为要映射的对象类型定义映射,列表应该“正常工作”

标签: automapper


【解决方案1】:

在您的 AutoMapper 定义中:

    CreateMap<MyStuffDTO, MyStuffViewModel>()
        .ForMember(dto => dto.MyDate, opt => opt.MapFrom(src => src.LastDate))
        .ForMember(dto => dto.MyTime, opt => opt.MapFrom(src => src.LastTime))
        .ForMember(dto => dto.Category, opt => opt.MapFrom(src => src.Category));

在代码中:

单身:

var result = Mapper.Map<MyStuffDTO, MyStuffViewModel>(obj);

对于列表:

var list = Mapper.Map<IList<MyStuffDTO>, IList<MyStuffViewModel>>(obj);

【讨论】:

  • [AutoMap(typeof(List), typeof(List))] 我可以在MVC中这样使用吗???
猜你喜欢
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 2019-04-26
  • 1970-01-01
  • 2019-03-30
  • 2017-07-20
  • 1970-01-01
相关资源
最近更新 更多