Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: passing parameter to Map method

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)); 
like image 641
davioooh Avatar asked Dec 21 '15 09:12

davioooh


People also ask

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

Can AutoMapper map enums?

The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.

Does AutoMapper map private fields?

AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.


1 Answers

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.

like image 91
Richard Avatar answered Sep 17 '22 12:09

Richard