Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to add extra parameter to Automapper ForMember

So, I have a mapping ObjectFrom to ObjectTo. ' All mappings can be done ObjectFrom.propX -> ObjectTo.propX2. But there is also a property in ObjectTo that needs to have a fixed value (for each mapping), lets call it "CallerName", that has nothing to do with ObjectFrom.

Can I in some way sneak in an extra parameter into the mapping? Id prefer not to wrap my ObjectFrom nor use AfterMap(), since I want to force caller to provide CallerName to make sure its gets filled.

When googling on this Ive found one solution more complex then the other. Is there a simple way to do this?

(Asp Net Core, latest version of automapper)

like image 327
Cowborg Avatar asked Sep 14 '25 09:09

Cowborg


1 Answers

When calling Map you can pass in extra objects by using key-value and a custom resolver to get the object from the mapping context.

mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");

This is how to setup the mapping for this custom resolver

cfg.CreateMap<Source, Dest>()
.ForMember(dest => dest.Foo, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["Foo"]);

The docs.

like image 137
Lucian Bargaoanu Avatar answered Sep 16 '25 23:09

Lucian Bargaoanu