'AutoMapper: Prevent Shallow Copy of Self-Mappings
I'm using AutoMapper (version 11.0.1) in a .NET 6 application, and one of its features seems to be that if you map a type to itself, it'll let you do that out of the box.
IMapper mapper = new MapperConfiguration(/* add profiles here */).CreateMapper();
Foo oldFoo = new Foo();
Foo myFoo = mapper.Map<Foo>(oldFoo); // Doesn't throw an exception.
The problem is that myFoo and oldFoo are the same reference/object. A new instance is not created! (You can verify this by using ReferenceEquals. It's doing a shallow copy.) You can mitigate this by adding a self-mapping to your AutoMapper profile.
public class MyProfile : AutoMapper.Profile
{
CreateMap<Foo, Foo>(); // Now calls to Map() will return a new instance.
}
My question: Is there a way to disable the behavior of "map non-specified self-mappings"? I would much rather AutoMapper throw the usual "no configurations found" exception and be explicit. There are some scenarios where I do not want to edit the new object, and therefore also edit the old object by side effect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
