Automapper - Does it map lists of objects?

Randy Minder picture Randy Minder · Nov 25, 2010 · Viewed 46.3k times · Source

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?

Answer

ozczecho picture ozczecho · Nov 26, 2010

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