I am working with AutoMapper and some of the values for the entity being mapped to are variables in my current method. I have tried to Google it but to no avail. Can I pass a set of KeyValue Pairs or an object or something to my mapping to have it use those values?
Sample of Post Mapping Modification
//comment variable is a Comment class instance
var imageComment = AutoMapper.Mapper.Map<Data.ImageComment>(comment);
//I want to pass in imageId so I dont have to manually add it after the mapping
imageComment.ImageId = imageId;
Objects can be passed to the resolver with the
Items
Dictionary option. The standard API to do this is pretty verbose (as seen in the accepted answer) but can be simplified nicely using a few extension methods:Which can be used like this:
If you have an object that you commonly need to pass to mapper resolvers (for example, the current user), you can go one step further and define more specialized extensions:
Which can be used like:
AutoMapper handles this key-value pair scenario out of the box.
Then at runtime:
A bit verbose to dig into the context items but there you go.
Suppose you have these two objects:
And you want to copy an existing object of type
ObjectA
into a new object of typeObjectB
, using AutoMapper you have to do this:For Automapper 6.0.2:
Profile:
Mapping: