Self referencing loop from Newtonsoft JsonSerializer using Entity Framework Core

后端 未结 1 672
滥情空心
滥情空心 2020-12-21 20:43

I\'ve encountered the error:

JsonSerializationException: Self referencing loop detected for property \'Subject\' with type \'Project.Models.Subject

相关标签:
1条回答
  • 2020-12-21 21:26

    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 (officially recommended). It works but still can result in serializing excessive data if self-reference occurs deep in the hierarchy.

    • [JsonIgnore] attribute on navigation properties. As you noted, attributes disappear when model classes are regenerated. Thus, their use can be inconvenient.

    • (Best choice) Pre-select a subset of properties:

      var minimallyNecessarySet= _nwind.Products.Select(p => new {
          p.ProductID,
          p.ProductName,
          p.UnitPrice,
          p.CategoryID
      });
      
      return minimallyNecessarySet.ToList();
      

      This approach has the advantage of serializing only required data. It's compatible with DevExtreme's DataSourceLoader:

      return DataSourceLoader.Load(minimallyNecessarySet, loadOptions);
      
    0 讨论(0)
提交回复
热议问题