11
votes

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?

1

1 Answers

19
votes

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