c# - Entity Framework 核心 .Include() 问题

标签 c# entity-framework-core

一直在尝试使用 ef core 并遇到 include 语句的问题。对于这段代码,我得到了 2 家公司,这是我所期望的。

public IEnumerable<Company> GetAllCompanies(HsDbContext db)
{
    var c = db.Company;
    return c;
}

返回

[
    {
        "id":1,
        "companyName":"new",
        "admins":null,
        "employees":null,
        "courses":null
    },
    {
        "id":2,
        "companyName":"Test Company",
        "admins":null,
        "employees":null,
        "courses":null
    }
]

如您所见,有 2 家公司,所有相关属性均为空,因为我没有使用任何包含项,这正是我所期望的。现在,当我将方法更新为:

public IEnumerable<Company> GetAllCompanies(HsDbContext db)
{
    var c = db.Company
        .Include(t => t.Employees)
        .Include(t => t.Admins)
        .ToList();

    return c;
}

这是它返回的内容:

[
    {
        "id":1,
        "companyName":"new",
        "admins":[
            {
                "id":2,
                "forename":"User",
                "surname":"1",
                "companyId":1
            }
        ]
    }
]

它只返回一家公司并且只包括管理员。为什么不包括这两家公司及其员工?

public class Company
{
    public int Id { get; set; }
    public string CompanyName { get; set; }
    public List<Admin> Admins { get; set; }
    public List<Employee> Employees { get; set; }
    public List<Course> Courses { get; set; }

    public string GetFullName()
    {
        return CompanyName;
    }
}

public class Employee
{
    public int Id { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }
    public int CompanyId { get; set; }
    [ForeignKey("CompanyId")]
    public Company company { get; set; }

    public ICollection<EmployeeCourse> Employeecourses { get; set; }
}

public class Admin
{
    public int Id { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }
    public int CompanyId { get; set; }
    [ForeignKey("CompanyId")]
    public Company Company { get; set; }
}

最佳答案

我不确定您是否看到了这个 question 的公认答案,但问题在于 JSON Serializer 如何处理循环引用。可以在上面的链接中找到完整的详细信息和指向更多引用的链接,我建议深入研究这些内容,但简而言之,将以下内容添加到 startup.cs 将配置序列化程序以忽略循环引用:

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

关于c# - Entity Framework 核心 .Include() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38550806/

相关文章:

c# - 关于 EF Core 中的 "owned"类型

c# - 在表达式中使用 Func?

c# - 检查是否已收到数据套接字 c#

c# - 同一类上的多对多关系不起作用

c# - EF Core 处理索引冲突的最佳实践

c# - 内存中的 EF Core SQLite 异常 : SQLite Error 1: 'near "MAX": syntax error'

c# - EF Core 无法确定抽象类中外键表示的关系

c# - 在列表上引用不改变值

c# - 如何链接接受 Func<> 委托(delegate)的方法重载? (C#)

c# - 如何将 C# double[] 传递给需要常量 double* pArr 的 C++ 函数? C++, C#