迁移到AutoMapper 5-循环引用 [英] Migrating to AutoMapper 5 - Circular references

查看:174
本文介绍了迁移到AutoMapper 5-循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在以前与AutoMapper 4一起使用的AutoMapper 5中映射某些内容时,出现了 System.StackOverflowException 的情况。

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.

AutoMapper文档说:

The AutoMapper Documentation says:


以前,AutoMapper可以通过跟踪
映射的内容来处理循环引用,然后在每次映射时,检查源/目标对象的本地
哈希表,以查看该项目是否已被
映射。事实证明,这种跟踪非常昂贵,您需要使用PreserveReferences选择
才能使圆形地图正常工作。
或者,您可以配置MaxDepth:

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();


所以我添加了 .MaxDepth(3 )到我的代码中,它现在又可以正常工作。

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 :)

我的问题:


  • 在问候方面意味着循环引用是什么意思/ CategoryDto类别?

  • .MaxDepth()到底是什么?为什么在示例中使用3?

  • .PreserveReferences()的用途是什么?

  • 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 将使地图的行为类似于 AutoMapper4 像往常一样。这将使 AutoMapper 跟踪所映射的内容,并防止其引起溢出。

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.

另一种方法是设置希望 AutoMapper 遍历的深度。设置深度后,它将映射指定次数的自引用模型。

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;}
}

引用自身的类,属性 Child 表示您可以多次嵌套此对象。

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

这篇关于迁移到AutoMapper 5-循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆