66

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?

3
  • Why do you have the same mapping twice? You should only define it once (presumably the second one) Commented Nov 25, 2010 at 13:43
  • 10
    @BeRecursive - Probably because I have a grand total of 2 hours experience with this tool. Commented Nov 25, 2010 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' Commented Nov 25, 2010 at 19:26

2 Answers 2

159

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);
Sign up to request clarification or add additional context in comments.

2 Comments

[AutoMap(typeof(List<Category>), typeof(List<CategoryViewModel>))] can I use it like this in MVC ???
this is outdated, Mapper is no more a static class. Check this stackoverflow.com/questions/58807216/… for an updated solution
0

Sometimes you can have exceptions not connected to Automepper. You need to check these main features for correct mappings:

  • Empty constructor for models
  • Similar types of lists
  • Create mappings for all included Properties but MAP only one time.

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.