[英]Controller crash when returning ef core objects with navigation properties
我的环境是Asp.Net Core 2.1 EF Core 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
{
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; }
}
在我的Api控制器中
// GET: api/Customers
[HttpGet]
public IEnumerable<Customer> GetCustomers()
{
var custlist = _context.Customers
.Include(c=>c.CustomerLocations)
.ToList();
return custlist;
}
我想收到这个JSON
[
{
id: 1,
name: "My First Company",
customerLocations: [
{
id: 1,
customerId: 1,
streetAddress: "13 Union Street",
zipCode: "94111",
city: "San Francisco",
state: "CA",
category: "Headquarter",
customer: null
},
{
id: 2,
customerId: 1,
streetAddress: "1098 Harrison St",
zipCode: "94103",
city: "San Francisco",
state: "CA",
category: "Warehouse",
customer: null
}]
},
{
id: 2,
name: "Another Company",
customerLocations: [ ]
}
]
但我收到的答案是
[
{
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
引用循环,并且如您将客户引用设置为null
时所说的那样,避免了引用循环。
处理它的另一种方法是在startup.cs
为Json序列化程序设置ReferenceLoopHandling
services
.AddMvc()
.AddJsonOptions(config =>
{
config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.