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

Controller crash when returning ef core objects with navigation properties

我的环境是 Asp.Net 核心 2.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
{
    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,但我不相信这是处理此问题的正确方法。

这个错误的原因是在序列化 Customer 时引用循环,正如您所说,当您将客户引用设置为 null 时,您避免了引用循环。

另一种处理方法是在 startup.cs

中为 Json 序列化程序设置 ReferenceLoopHandling
services
    .AddMvc()
    .AddJsonOptions(config =>
    {
        config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });