Self referencing loop from Newtonsoft JsonSerializer using Entity Framework Core(使用 Entity Framework Core 的 Newtonsoft JsonSerializer 的自引用循环)
问题描述
我遇到了错误:
JsonSerializationException:检测到自引用循环属性主题",类型为Project.Models.Subject".小路'数据[0].总计'.
JsonSerializationException: Self referencing loop detected for property 'Subject' with type 'Project.Models.Subject'. Path 'data[0].Totals'.
当我使用由 IEnumerable<Subject>
模型填充的 dataGrid 加载视图时,会发生这种情况.Grid 是一个 DevExtreme DataGrid 绑定到 View 的模型,如下所示:
It occurs when I load a View with a dataGrid populated by an IEnumerable<Subject>
model. The Grid is a DevExtreme DataGrid bound to the View's model like this:
@(Html.DevExtreme().DataGrid()
.DataSource(Model)
.Paging(paging =>
{
paging.Enabled(true);
paging.PageIndex(0);
paging.PageSize(20);
})
.Columns(columns =>
{
columns.Add().DataField("SubjectId");
... other fields
})
)
从使用此功能从存储库中提取数据的控制器填充:
Which is populated from a Controller that pulls data from a Repository with this function:
public async Task<IEnumerable<Subject>> GetSubjectsAsync()
{
return await _context.Subject.ToListAsync();
}
Subject 表与 Totals 具有 1:1 的关系,其中 Totals 具有对 Subject 的外键引用.项目中的模型如下所示(由 Scaffold-DbContext 生成):
The Subject table has a 1:1 relationship with Totals with Totals having a foreign key reference to Subject. The Models in the project look like this (generated from Scaffold-DbContext):
public partial class Subject
{
public Guid SubjectId { get; set; }
public virtual Totals Totals { get; set; }
}
public partial class Totals
{
public Guid TotalsId { get; set; }
public virtual Subject Subject { get; set; }
}
由于 2 个对象相互引用,因此在序列化时会导致循环.为了纠正这个问题,我将此配置添加到我的 Startup.ConfigureServices 方法中:
Since the 2 objects reference eachother it causes a loop when serializing it. To correct this I added this config to my Startup.ConfigureServices method:
services.AddMvc()
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
我从这个答案中得到:https://stackoverflow.com/a/40501464/7897176
但是,这并不能解决问题,当我加载涉及主题的视图时,它仍然会导致错误.将 [JsonIgnore]
添加到 Totals 的 Subject 属性可以解决问题,但是我不想将其添加到模型中的每个子属性中,并且每当我更新模型时都必须重做数据库.
However this doesn't fix the problem and its still causing an error when I load a view that involves Subjects. Adding [JsonIgnore]
to the Subject property of Totals fixes the problem, but I don't want to have to add that to every child property in my models and have to redo it whenever I update my models from the db.
推荐答案
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);
这篇关于使用 Entity Framework Core 的 Newtonsoft JsonSerializer 的自引用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Entity Framework Core 的 Newtonsoft JsonSerializer 的自引用循环
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01