自动映射器:将参数传递给Map方法 [英] Automapper: passing parameter to Map method

查看:42
本文介绍了自动映射器:将参数传递给Map方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用 Automapper ,并且需要动态评估目标对象的字段.

I'm using Automapper in a project and I need to dynamically valorize a field of my destination object.

在我的配置中,我有类似的内容:

In my configuration I have something similar:

cfg.CreateMap<Message, MessageDto>()
    // ...
    .ForMember(dest => dest.Timestamp, opt => opt.MapFrom(src => src.SentTime.AddMinutes(someValue)))
    //...
    ;

配置代码中的 someValue 是我在运行时需要传递给映射器的参数,而不是源对象的字段.

The someValue in the configuration code is a parameter that I need to pass at runtime to the mapper and is not a field of the source object.

有没有办法做到这一点?像这样:

Is there a way to achieve this? Something like this:

Mapper.Map<MessageDto>(msg, someValue));

推荐答案

您不能完全执行所需的操作,但是在调用Map时可以通过指定映射选项来达到非常接近的效果.忽略配置中的属性:

You can't do exactly what you want, but you can get pretty close by specifying mapping options when you call Map. Ignore the property in your config:

cfg.CreateMap<Message, MessageDto>()
    .ForMember(dest => dest.Timestamp, opt => opt.Ignore());

然后在调用地图时传递选项:

Then pass in options when you call your map:

int someValue = 5;
var dto = Mapper.Map<Message, MessageDto>(message, opt => 
    opt.AfterMap((src, dest) => dest.TimeStamp = src.SendTime.AddMinutes(someValue)));

请注意,您需要使用 Mapper.Map< TSrc,TDest> 重载才能使用此语法.

Note that you need to use the Mapper.Map<TSrc, TDest> overload to use this syntax.

这篇关于自动映射器:将参数传递给Map方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆