I have a source object which contains 2 references to the same collection. If I map the source type to a structurally-equivalent target type, AutoMapper will create two instances of the collection in the target instance.
class SourceThing
{
public string Name { get; set; }
public List<int> Numbers { get; set; }
public List<int> MoreNumbers { get; set; }
}
class TargetThing
{
public string Name { get; set; }
public List<int> Numbers { get; set; }
public List<int> MoreNumbers { get; set; }
}
If I create a SourceThing
which has two references to the same List, map it to a TargetThing
, the result is a TargetThing
with two separate instances of the collection.
public void MapObjectWithTwoReferencesToSameList()
{
Mapper.CreateMap<SourceThing, TargetThing>();
//Mapper.CreateMap<List<int>, List<int>>(); // passes when mapping here
var source = new SourceThing() { Name = "source" };
source.Numbers = new List<int>() { 1, 2, 3 };
source.MoreNumbers = source.Numbers;
Assert.AreSame(source.Numbers, source.MoreNumbers);
var target = Mapper.Map<TargetThing>(source);
Assert.IsNotNull(target.Numbers);
Assert.AreSame(target.Numbers, target.MoreNumbers); // fails
}
Is this meant to be the default mapping behavior for concrete collections in AutoMapper? Through testing, I realized that if I mapped List<int>
to List<int>
, I achieve the behavior I want, but I don't understand why. If AutoMapper tracks references and doesn't re-map a mapped object, wouldn't it see that the source.MoreNumbers
points to the same list as source.Numbers
, and set the target accordingly?