返回具有导航属性的ef核心对象时控制器崩溃



我的环境是Asp.Net核心2.1EF 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;
});

最新更新