Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper auto create createMap

Tags:

I have a services that is calling another services. Both of the services are using "the same classes". The classes are named same and have the same properties but has different namespace so I need to use AutoMapper to map from one of the type to the other type.

No it's pretty simple since all I have to do is the CreateMap<>, but the problem is that we have around hundreds of classes that I manually needs to write the CreateMap<> from, and it's works wired to me. Isn't there any Auto CreateMap function. So if I say CreateMap() then AutoMapper workes thru Organisation and finds all classes and automatically does the CreateMap for these Classes and it's subclasses etc etc…

Hope for a simple solution, or I guess some reflection can fix it...

like image 556
Magnus Gladh Avatar asked Jun 13 '13 11:06

Magnus Gladh


1 Answers

Just set CreateMissingTypeMaps to true in the options:

var dto = Mapper.Map<FooDTO>      (foo, opts => opts.CreateMissingTypeMaps = true); 

If you need to use it often, store the lambda in a delegate field:

static readonly Action<IMappingOperationOptions> _mapperOptions =     opts => opts.CreateMissingTypeMaps = true;  ...  var dto = Mapper.Map<FooDTO>(foo, _mapperOptions); 

UPDATE:

The approach described above no longer works in recent versions of AutoMapper.

Instead, you should create a mapper configuration with CreateMissingTypeMaps set to true and create a mapper instance from this configuration:

var config = new MapperConfiguration(cfg => {     cfg.CreateMissingTypeMaps = true;     // other configurations }); var mapper = config.CreateMapper(); 

If you want to keep using the old static API (no longer recommended), you can also do this:

Mapper.Initialize(cfg => {     cfg.CreateMissingTypeMaps = true;     // other configurations }); 

UPDATE 2 - Automapper 9 and later:

Starting from Automapper version 9.0, the CreateMissingTypeMaps API was removed. Automapper documentation now suggests to explicitly configure maps, manually or using reflection.

https://docs.automapper.org/en/stable/9.0-Upgrade-Guide.html#automapper-no-longer-creates-maps-automatically-createmissingtypemaps-and-conventions

like image 107
Thomas Levesque Avatar answered Sep 28 '22 03:09

Thomas Levesque