I\'ve encountered the error:
JsonSerializationException: Self referencing loop detected for property \'Subject\' with type \'Project.Models.Subject
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);