Automapper: use source and destination together in mapping

Is it possible, in Automapper, to associate a source with a receiver when setting up String property mapping? I thought I could just do something:

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

However, in lambda, MapFrom d clearly not in scope. Any suggestions on how to combine source and target values ​​in my mapping?

+6
source share
1 answer

You can do this using AfterMap , which concatenates 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 script

+9
source

Source: https://habr.com/ru/post/980808/


All Articles