Search code examples
c#asp.net-mvcautomapper

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?


Solution

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