Automapper-来自2个来源的地图实体

时间:2019-05-03 19:15:20

标签: c# asp.net-core .net-core automapper

我正在编写一个ASP网络核心控制器方法,其中我在路径( agentID )中接收部分请求,而在主体( scenarioReq )中接收另一部分请求。我必须使用Automapper将这两个输入映射到单个实体中。

我完成的方式很丑陋(我没有在 Map 调用后分配AgentId属性,以便成为一条指令)

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

有人知道是否有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用ResolutionContext并将agentId作为额外的字典项传递:

//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);