63

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?

Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • Why do you have the same mapping twice? You should only define it once (presumably the second one) – BeRecursive Nov 25 '10 at 13:43
  • 8
    @BeRecursive - Probably because I have a grand total of 2 hours experience with this tool. – Randy Minder Nov 25 '10 at 14:46
  • Well i should work with lists out of the box as long as you define the mapping correctly. Do you mean lists of the above type? You don't need to define mappings for lists of explicit objects, just define the mappings for the type of object you want to map and lists should 'just work' – BeRecursive Nov 25 '10 at 19:26

1 Answers1

155

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);
ozczecho
  • 8,649
  • 8
  • 36
  • 42
  • [AutoMap(typeof(List), typeof(List))] can I use it like this in MVC ??? – dnxit Mar 13 '13 at 23:24
  • this is outdated, Mapper is no more a static class. Check this https://stackoverflow.com/questions/58807216/automapper-object-reference-is-required-for-the-non-static-field-method-or-prop for an updated solution – Defkon1 Nov 07 '22 at 09:12