Automapper: passing parameter to Map method

让人想犯罪 __ 提交于 2019-12-20 11:49:38

问题


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

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

回答1:


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

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




回答2:


Another possible option while using the Map method would be the usage of the Items dictionary. Example:

int someValue = 5;
var dto = Mapper.Map<Message>(message, 
    opts => opts.Items["Timestamp"] = message.SentTime.AddMinutes(someValue));

It's a little bit less code and has the advantage of dynamically specified fields.



来源:https://stackoverflow.com/questions/34392569/automapper-passing-parameter-to-map-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!