C# 返回具有导航属性的ef核心对象时控制器崩溃
我的环境是 Asp.NETCore2.1 EF核心2.1C# 返回具有导航属性的ef核心对象时控制器崩溃,c#,asp.net-core,ef-core-2.1,C#,Asp.net Core,Ef Core 2.1,我的环境是 Asp.NETCore2.1 EF核心2.1 public class Customer { public int Id { get; set; } public string name { get; set; } public virtual ICollection<CustomerLocation> CustomerLocations { get; set; } public class CustomerLocation { pu
public class Customer
{
public int Id { get; set; }
public string name { get; set; }
public virtual ICollection<CustomerLocation> CustomerLocations { get; set; }
public class CustomerLocation
{
public int Id { get; set; }
public int customerId { get; set; }
public string streetAddress { get; set; }
public string zipCode { get; set; }
public string city { get; set; }
public string state { get; set; }
public string category { get; set; }
public virtual Customer Customer { get; set; }
}
但我得到的答案是
[
{
id: 1,
name: "My First Company",
customerLocations: [
{
id: 1,
customerId: 1,
streetAddress: "13 Union Street",
zipCode: "94111",
city: "San Francisco",
state: "CA",
category: "Headquarter"
然后,它在尝试循环到“customerLocation”的“customer”导航属性时崩溃
我发现解决这个问题的唯一方法是显式地为每个CustomerLocation中的所有“customer”引用设置空值,但我不相信这是正确的处理方法 此错误的原因是序列化
Customer
时的引用循环,正如您在将Customer Reference设置为null
时所说的,您避免了引用循环
另一种处理方法是在startup.cs
中为Json序列化程序设置ReferenceLoopHandling
services
.AddMvc()
.AddJsonOptions(config =>
{
config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
此错误的原因是序列化
Customer
时的引用循环,正如您在将Customer Reference设置为null
时所说的,您避免了引用循环
另一种处理方法是在startup.cs
中为Json序列化程序设置ReferenceLoopHandling
services
.AddMvc()
.AddJsonOptions(config =>
{
config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
有什么例外吗?@ofiris我没有例外。如果调试控制器执行,则在执行return语句之前,一切都正常。然后在浏览器中,我只在“customer”属性之前截断了一个JSON结构。如果我使用Postman&Fiddler,我会得到以下响应“[Fiddler]ReadResponse()失败:服务器没有对此请求返回完整响应。服务器返回530字节。”您可能会在这里找到解决方案@karan谢谢您的参考,但它似乎过时了(8年前);这一定是EF core 2.1的问题,我在EF6中没有这个问题。在序列化模型时,JSON.Net正在查找循环引用并中断。您可以使用[JsonIgnore]属性装饰CustomerLocation类中的“Customer”属性,也可以使用@configuration来处理此问题。另外,请阅读与这两种方法相关的问题。例外情况是什么?@ofiris我不能得到任何例外。如果调试控制器执行,则在执行return语句之前,一切都正常。然后在浏览器中,我只在“customer”属性之前截断了一个JSON结构。如果我使用Postman&Fiddler,我会得到以下响应“[Fiddler]ReadResponse()失败:服务器没有对此请求返回完整响应。服务器返回530字节。”您可能会在这里找到解决方案@karan谢谢您的参考,但它似乎过时了(8年前);这一定是EF core 2.1的问题,我在EF6中没有这个问题。在序列化模型时,JSON.Net正在查找循环引用并中断。您可以使用[JsonIgnore]属性装饰CustomerLocation类中的“Customer”属性,也可以使用@configuration来处理此问题。另外,请阅读与这两种方法相关的问题。
services
.AddMvc()
.AddJsonOptions(config =>
{
config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});