Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - Multi object source and one destination

I am using auto mapper to map multiple objects (db class into ui objects).

Map 1:

Mapper.CreateMap<sourceone, destination>().ForMember(sss => sss.one, m => m.MapFrom(source => source.abc)); 

Map 2:

Mapper.CreateMap<sourcetwo, destination>().ForMember(sss => sss.two, m => m.MapFrom(source => source.xyz));  destination d = new destination(); 

//Map 1

d = AutoMapper.Mapper.Map<sourceone, destination>(sourceone); 

//Map 2

d = AutoMapper.Mapper.Map<sourcetwo, destination>(sourcetwo); 

Once I make call to the 'Map 2', the values that are populated using Map 1 are lost.. (i.e destination.one is becoming empty). How do I fix this?

like image 524
CoolArchTek Avatar asked Oct 23 '13 14:10

CoolArchTek


People also ask

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.

Is AutoMapper bidirectional?

What is AutoMapper Reverse Mapping in C#? The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.


2 Answers

Map has an overload that takes a source and destination object:

d = AutoMapper.Mapper.Map<sourceone, destination>(sourceone);  /* Pass the created destination to the second map call: */ AutoMapper.Mapper.Map<sourcetwo, destination>(sourcetwo, d); 
like image 165
Andrew Whitaker Avatar answered Oct 11 '22 10:10

Andrew Whitaker


mapper.MergeInto<PersonCar>(person, car) 

with the accepted answer as extension-methods, simple and general version:

public static TResult MergeInto<TResult>(this IMapper mapper, object item1, object item2) {     return mapper.Map(item2, mapper.Map<TResult>(item1)); }  public static TResult MergeInto<TResult>(this IMapper mapper, params object[] objects) {     var res = mapper.Map<TResult>(objects.First());     return objects.Skip(1).Aggregate(res, (r, obj) => mapper.Map(obj, r)); } 

after configuring mapping for each input-type:

IMapper mapper = new MapperConfiguration(cfg => {     cfg.CreateMap<Person, PersonCar>();     cfg.CreateMap<Car, PersonCar>(); }).CreateMapper(); 
like image 27
Grastveit Avatar answered Oct 11 '22 11:10

Grastveit