I'm having a System.StackOverflowException
when trying to Map something in AutoMapper 5 that worked previously with AutoMapper 4.
After googling a bit around I found out that it caused by Circular references.
The AutoMapper Documentation says:
Previously, AutoMapper could handle circular references by keeping track of what was mapped, and on every mapping, check a local hashtable of source/destination objects to see if the item was already mapped. It turns out this tracking is very expensive, and you need to opt-in using PreserveReferences for circular maps to work. Alternatively, you can configure MaxDepth:
// Self-referential mapping cfg.CreateMap<Category, CategoryDto>().MaxDepth(3); // Circular references between users and groups cfg.CreateMap<User, UserDto>().PreserveReferences();
So I added .MaxDepth(3)
to my code and it works now again.
However I do not undertand what the real problem is and what I did by adding the line :)
My Questions:
- What means 'circular references' in regards of Category/CategoryDto ?
- What exactly does
.MaxDepth()
? Why 3 is used in the sample? - What is
.PreserveReferences()
for?
PreserveReferences
will make the map behave likeAutoMapper4
as you are used to. It will makeAutoMapper
keep track of what is mapped and prevent it from causing an overflow.The other option is to set a depth that you wish
AutoMapper
to traverse. With a set depth it will map a self referencing model the number of times specified.Circular references would be a class such as:
A class referencing itself, property
Child
means you can nest this object many times.