自动映射 - 是否映射对象列表?

时间:2010-11-25 11:44:34

标签: automapper

我有以下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());

当我映射单个对象时,这可以正常工作。但我似乎无法传递对象列表。传入列表时是否需要不同的定义,或者不可能?

1 个答案:

答案 0 :(得分:131)

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