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

时间:2018-07-29 05:49:53

标签: c# asp.net-core ef-core-2.1

我的环境是 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中显式将所有“客户”引用无效,但是我不认为这是处理此问题的正确方法。

1 个答案:

答案 0 :(得分:2)

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

您可以处理的另一种方法是在ReferenceLoopHandling中为Json序列化器设置startup.cs

services
    .AddMvc()
    .AddJsonOptions(config =>
    {
        config.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });