迁移到 AutoMapper 5 - 循环引用
Migrating to AutoMapper 5 - Circular references
当我尝试在 AutoMapper 5 中映射以前与 AutoMapper 4 一起工作的内容时,我遇到了 System.WhosebugException
。
谷歌搜索了一下后,我发现它是由 Circular references.
引起的
AutoMapper 文档说:
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)
添加到我的代码中,它现在又可以工作了。
但是我不明白真正的问题是什么以及我通过添加行:)
做了什么
我的问题:
- 'circular references' 对于 Category/CategoryDto 是什么意思?
.MaxDepth()
究竟是什么?为什么示例中使用 3?
.PreserveReferences()
有什么用?
PreserveReferences
将使地图表现得像您习惯的 AutoMapper4
一样。它将使 AutoMapper
跟踪映射的内容并防止它导致溢出。
另一个选项是设置您希望 AutoMapper
遍历的深度。使用设定的深度,它将映射一个自引用模型指定的次数。
循环引用可以是 class 例如:
public class Category
{
public int Id {get;set;}
public Category Child {get;set;}
public string Value {get;set;}
}
一个class引用自身,属性Child
表示你可以多次嵌套这个对象
当我尝试在 AutoMapper 5 中映射以前与 AutoMapper 4 一起工作的内容时,我遇到了 System.WhosebugException
。
谷歌搜索了一下后,我发现它是由 Circular references.
引起的AutoMapper 文档说:
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)
添加到我的代码中,它现在又可以工作了。
但是我不明白真正的问题是什么以及我通过添加行:)
做了什么我的问题:
- 'circular references' 对于 Category/CategoryDto 是什么意思?
.MaxDepth()
究竟是什么?为什么示例中使用 3?.PreserveReferences()
有什么用?
PreserveReferences
将使地图表现得像您习惯的 AutoMapper4
一样。它将使 AutoMapper
跟踪映射的内容并防止它导致溢出。
另一个选项是设置您希望 AutoMapper
遍历的深度。使用设定的深度,它将映射一个自引用模型指定的次数。
循环引用可以是 class 例如:
public class Category
{
public int Id {get;set;}
public Category Child {get;set;}
public string Value {get;set;}
}
一个class引用自身,属性Child
表示你可以多次嵌套这个对象