更新时间:2023-01-17 23:03:54
JSON 序列化过程中的自引用循环问题与 EFCore 如何加载相关数据有关 (docs).加载集合时,相关实体可能会或可能不会自动填充,具体取决于这些对象之前是否已加载.这称为导航属性的自动修复.或者,它们可以通过 .Include()
.
The problem of self-referencing loops during JSON serialization is connected to how EFCore loads related data (docs). When you load a collection, related entities may or may not be automatically populated depending on whether or not those object have been previously loaded. It's called automatic fix-up of navigation properties. Alternatively, they may be eagerly loaded via .Include()
.
每当您获得要序列化的实体的自引用图时,有几种选择:
Whenever you get a self-referencing graph of entities to be serialized, there are several options:
Newtonsoft.Json.ReferenceLoopHandling.Ignore
(官方推荐).如果自引用发生在层次结构的深处,它可以工作,但仍然会导致序列化过多的数据.
Newtonsoft.Json.ReferenceLoopHandling.Ignore
(officially recommended). It works but still can result in serializing excessive data if self-reference occurs deep in the hierarchy.
[JsonIgnore]
导航属性上的属性.正如您所指出的,重新生成模型类时,属性会消失.因此,它们的使用可能会很不方便.
[JsonIgnore]
attribute on navigation properties. As you noted, attributes disappear when model classes are regenerated. Thus, their use can be inconvenient.
(***选择) 预选属性子集:
var minimallyNecessarySet= _nwind.Products.Select(p => new {
p.ProductID,
p.ProductName,
p.UnitPrice,
p.CategoryID
});
return minimallyNecessarySet.ToList();
这种方法的优点是仅序列化所需的数据.它与 DevExtreme 的 DataSourceLoader
兼容:
This approach has the advantage of serializing only required data. It's compatible with DevExtreme's DataSourceLoader
:
return DataSourceLoader.Load(minimallyNecessarySet, loadOptions);