automapper configuration to automatically map entity to same entity

290 Views Asked by At

Is there a way to configure AutoMapper to make it automatically map an entity to itself...

I want to avoid this basically:

    Mapper.CreateMap<Company, Company>();
    Mapper.CreateMap<Car, Car>();
....
1

There are 1 best solutions below

0
On

You can make use of DynamicMap, without configuring CreateMap:

var companyMapped = Mapper.DynamicMap<Company>(company);

The DynamicMap call creates a configuration for the type of the source object passed in to the destination type specified. If the two types have already been mapped, AutoMapper skips this step (as I can call DynamicMap multiple times for this example). To be safe, AutoMapper will validate the configuration for a dynamic map the first time executed, as it tends to give better messages than a mapping exception.

With DynamicMap, you don’t have the luxury of configuring the mapping, but at this point, you’ve also lost the benefits of a single AssertConfigurationIsValid call. In the DynamicMap side, I could lower the bar quite a bit and not do any mapping validation, but I’d rather not as its intended use is a very specific scenario. The ideal case is to configure your mappings up front, for much better testability.