automapper

Automapper - Does it map lists of objects?


I have the following Automapper defintion:

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

This works fine when I map a single object. But I can't seem to pass in Lists of objects. Do I need a different definition when passing in a list, or is it not possible?


Solution

  • In your AutoMapper Definition:

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

    In code:

    For Single:

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

    For List:

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