Migrating to AutoMapper 5 - Circular references

无人久伴 提交于 2019-11-29 23:32:53

问题


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?

回答1:


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.



来源:https://stackoverflow.com/questions/40650571/migrating-to-automapper-5-circular-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!