Migrating to AutoMapper 5 - Circular references
Asked Answered
T

1

2

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?
Thessalonians answered 17/11, 2016 at 9:3 Comment(0)
S
5

PreserveReferences will make the map behave like AutoMapper4 as you are used to. It will make AutoMapper 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:

public class Category
{
    public int Id {get;set;}
    public Category Child {get;set;}
    public string Value {get;set;}
}

A class referencing itself, property Child means you can nest this object many times.

Sheath answered 17/11, 2016 at 11:9 Comment(1)
I set Depth as 1. Still stack overflows...! It feels like noway the configuration is listening to us...Felting

© 2022 - 2024 — McMap. All rights reserved.