一直在玩ef核心,並且對include語句有問題。對於這個代碼,我得到了2家公司,這是我的預期。實體框架核心.Include()問題
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只股票,因爲我havnt使用任何包含,這是我所期待的所有相關的屬性爲null。現在,當我更新的方法是:
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}]
}]
它只返回一個公司,只包括管理員。爲什麼它不包括2家公司和他們的員工?
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; }
}
您是否嘗試過使用EF 6或更低版本的相同代碼? –
你的EF版本是什麼? – Mafii
@Mafii,它是EF Core - EF 7,請參閱標題 –