When AutoMapper encounters an object that\'s already been mapped, it seems to use that object again, instead of trying to re-map it. I believe it does this based on .Equal
I also get the same issue. It doesn't happen when you map the same object twice - it happens when you have a tree heirarcy of objects, and the same value exists in two places of the tree (but with different child values) When mapping the second instance of the item - it uses the child values of the first instance, instead of re-evaluating what the child values should be.
Here is my example:
class Tag {
int Id {get; set;}
string Name {get; set;}
IEnumerable ChildTags {get; set;}
}
public void Test()
{
var source = new List
{
new Tag { Id = 1, Name = "Tag 1", ChildTags = new List
{
new Tag { Id = 2, Name = "Tag 2", ChildTags = new List
{
new Tag {Id = 3, Name = "Tag 3"},
new Tag {Id = 4, Name = "Tag 4"}
}
}
}
},
new Tag { Id = 1, Name = "Tag 1" },
new Tag {
Id = 3, Name = "Tag 3", ChildTags = new List
{
new Tag {Id = 4, Name = "Tag 4"}
}
}
};
Mapper.CreateMap()
.ForMember(dest => dest.ChildTags,
opt => opt.MapFrom(src => src.ChildTags));
var result = Mapper.Map, IList>(tags);
}
In the result
the first instance of Tag 1 (ie source[0]) and all of its children are perfect
the second instance of Tag 1 (ie source[1]) has all the children of the first instance - it should not have any children
the second instance of Tag 3 (ie source[2]) does not have any children - it should have Tag 4 as a child