Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - Does it map lists of objects?

Tags:

automapper

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?

like image 399
Randy Minder Avatar asked Nov 25 '10 11:11

Randy Minder


People also ask

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

Why you should not use AutoMapper?

1. If you use the convention-based mapping and a property is later renamed that becomes a runtime error and a common source of annoying bugs. 2. If you don't use convention-based mapping (ie you explicitly map each property) then you are just using automapper to do your projection, which is unnecessary complexity.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.


1 Answers

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); 
like image 64
ozczecho Avatar answered Oct 03 '22 07:10

ozczecho