Cowborg
Cowborg

Reputation: 2871

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)

Upvotes: 4

Views: 2978

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

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.

Upvotes: 6

Related Questions