Is this possible?
cfg.Default.ShallowCopyForSameType(true);
// Attempted code:
cfg.NewConfig<MyStuff, MyStuff>().ShallowCopyForSameType(false);
Trying to replicate similar behavior in the following:
// Source - https://stackoverflow.com/a/31677062
// Posted by Jimmy Bogard
// Retrieved 2026-04-28, License - CC BY-SA 3.0
You're reusing a type on both the source and destination objects, "MyStuff". When AutoMapper sees two assignable types, it assigns them rather than copying them. You can override this behavior by creating an explicit map:
Mapper.CreateMap<MyStuff, MyStuff>();
AutoMapper defaults to assigning, as AutoMapper is not a copying/cloning library.
Concerns
- While I'm trying out attempted code, some passes and some fails the unit test wherein the failed attempted code always had an error
System.NullReferenceException : Object reference not set to an instance of an object..
- These are only occurring for objects that has their own parameterless constructor that instantiates their uninitialized object properties if it's still null.
public FailingMyStuff() { CreateEmptyEntities(); }
public void CreateEmptyEntities() { Item1 ??= new(); Item2 ??= new(); }
- Although it can be fixed using
MapWith and defining a function, let's say MapToSelf, where it's general structure is return src == null ? null : new MyStuff(){ ... }; and I've verified that this passed the failing unit tests.
However, I wanted to know if there's a better way in automating this instead of using MapToSelf.
Is this possible?
Trying to replicate similar behavior in the following:
Concerns
System.NullReferenceException : Object reference not set to an instance of an object..MapWithand defining a function, let's sayMapToSelf, where it's general structure isreturn src == null ? null : new MyStuff(){ ... };and I've verified that this passed the failing unit tests.However, I wanted to know if there's a better way in automating this instead of using
MapToSelf.