0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.