我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
我尝试序列化从实体数据模型.edmx自动生成的POCO类,当我使用
JsonConvert.SerializeObject
我得到了以下错误:
为System.data.entity类型检测到自我引用循环错误。
我怎么解决这个问题?
当前回答
在。net 5中。使用下面的代码更新startup.cs中的ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
----------------
----------------
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
------------------
}
默认情况下,序列化(System.Text.Json.Serialization)不支持带周期的对象,也不保留重复引用。使用Preserve可以在序列化时保存唯一的对象引用,并在反序列化时使用元数据读取保存的引用。 MSDN链接
其他回答
您也可以将属性应用到属性。 [JsonProperty(ReferenceLoopHandling =…)属性非常适合这一点。
例如:
/// <summary>
/// Represents the exception information of an event
/// </summary>
public class ExceptionInfo
{
// ...code omitted for brevity...
/// <summary>
/// An inner (nested) error.
/// </summary>
[JsonProperty( ReferenceLoopHandling = ReferenceLoopHandling.Ignore, IsReference = true )]
public ExceptionInfo Inner { get; set; }
// ...code omitted for brevity...
}
希望有帮助, 扬
团队:
这适用于ASP。核心网;上面的挑战是如何“设置为忽略”。根据您设置应用程序的方式,这可能相当具有挑战性。以下是对我有效的方法。
这可以放在你的公共void ConfigureServices(IServiceCollection services)部分。
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
对我来说,我必须走不同的路线。而不是试图修复JSON。我必须在我的数据上下文的惰性加载之后。
我刚刚添加了这个到我的基本库:
context.Configuration.ProxyCreationEnabled = false;
“context”对象是我在基本存储库中使用的构造函数参数,因为我使用依赖注入。您可以在实例化数据上下文的任何地方更改ProxyCreationEnabled属性。
http://techie-tid-bits.blogspot.com/2015/09/jsonnet-serializer-and-error-self.html
没有循环这为我工作- ReferenceLoopHandling =引用eloophandling。忽略,
我已经在这里解决了所有问题——实体框架子序列化与。net Core 2 WebAPI https://gist.github.com/Kaidanov/f9ad0d79238494432f32b8407942c606
感谢任何评论。 也许有人可以用一下。
如果你使用的是。net Core 2。x,更新Startup.cs中的ConfigureServices部分
https://learn.microsoft.com/en-us/ef/core/querying/related-data/serialization
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}
如果你使用的是。net Core 3。x - 5.0,没有MVC,它将是:
# startup.cs
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
对于。net 6.0,唯一的不同是它现在进入Program.cs。
# program.cs
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
如果你使用实体框架和数据库优先的设计模式,这个引用循环处理几乎是强制性的。