Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: use source and destination together in mapping

Tags:

c#

automapper

Is it possible, in Automapper, to concatenate the source with the destination when configuring a mapping of String properties? I thought I could just do something this:

Mapper.CreateMap<Foo, Bar>()
   .ForMember(d => d.Notes, opt => opt.MapFrom(s => d.Notes + s.Notes)));
...
Mapper.Map<Foo, Bar>(source, destination);

However, in the MapFrom lambda, d obviously isn't in scope. Any suggestions on how to combine the source and destination values in my mapping?

like image 749
Patrick Szalapski Avatar asked Jan 10 '15 18:01

Patrick Szalapski


1 Answers

You can do this with an AfterMap which does the concatenation as follows:

Mapper.CreateMap<Foo, Bar>()
.ForMember(dest => dest.Notes, opt => opt.Ignore()) 
.AfterMap((src, dest) => dest.Notes = string.Concat(dest.Notes, src.Notes));

var source = new Foo { Notes = "A note" };

var destination = new Bar { Notes = "B note" };

Mapper.Map<Foo, Bar>(source, destination);

Console.WriteLine(destination.Notes);

Working Fiddle

like image 98
hutchonoid Avatar answered Nov 15 '22 16:11

hutchonoid