且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Entity Framework Core 的 Newtonsoft JsonSerializer 的自引用循环

更新时间:2023-01-18 08:12:35

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