简体   繁体   中英

Migrating to AutoMapper 5 - Circular references

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM