gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:43:01 29 4
gpt4 key购买 nike

一直在尝试使用 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com