迁移到AutoMapper 5 – 循环引用
尝试在AutoMapper 5中映射之前使用AutoMapper 4工作的东西时,我遇到了System.StackOverflowException
。
谷歌搜索后,我发现它是由循环引用引起的。
AutoMapper文档说:
以前,AutoMapper可以通过跟踪映射的内容来处理循环引用,并在每个映射上检查源/目标对象的本地哈希表,以查看该项是否已映射。 事实certificate,这种跟踪非常昂贵,您需要使用PreserveReferences选择使用圆形贴图才能工作。 或者,您可以配置MaxDepth:
// Self-referential mapping cfg.CreateMap().MaxDepth(3); // Circular references between users and groups cfg.CreateMap().PreserveReferences();
所以我将.MaxDepth(3)
添加到我的代码中,它现在再次运行。
但是我没有说明真正的问题是什么以及我通过添加线路做了什么:)
我的问题:
- 什么意思是关于Category / CategoryDto的’循环引用’?
- 到底是什么
.MaxDepth()
? 为什么样品中使用了3? - 什么是
.PreserveReferences()
?
PreserveReferences
将使您的地图像您习惯的那样表现得像AutoMapper4
。 它将使AutoMapper
跟踪映射的内容并防止它导致溢出。
另一个选项是设置您希望AutoMapper
遍历的深度。 使用设定的深度,它将根据指定的次数映射自引用模型。
循环引用将是一个类,如:
public class Category { public int Id {get;set;} public Category Child {get;set;} public string Value {get;set;} }
引用自身的类,属性Child
表示您可以多次嵌套此对象。