简体   繁体   中英

Automapper - Map Entity from 2 sources

I am writing an asp net core controller method where I am receiving part of the request in path ( agentID ) and the other in body ( scenarioReq ). I have to map this two inputs into a single entity with Automapper.

The way I have accomplished that is kind of ugly (I am not assigning the AgentId property after the Map call in order to be a single instruction):

_mapper.Map<ChangeScenarioRequest, Scenario>(scenarioReq, opt => opt.AfterMap((_, dest) => dest.AgentId = agentID));

Does someone know if there is a better way to do this?

You could use the ResolutionContext and pass the agentId as an extra dictionary item:

//In your mapping profile for <ChangeScenarioRequest, Scenario>
...your current member mappings
.ForMember(dest => dest.AgentId, opt.MapFrom((src, dest, destMember, ctx) => (string)ctx.Items["AgentId"]));

//Wherever you are doing the mapping
_mapper.Map<ChangeScenarioRequest, Scenario>(scenarioReq, opts => opts.Items["AgentId"] = agentId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM