实体框架4.1 POCO -多对多加载

本文关键字:加载 POCO 框架 实体 | 更新日期: 2023-09-27 18:14:17

我有以下4个表格(针对这个问题简化了):


公司

CompanyId | Name

<标题>员工

employeeid | CompanyId | FirstName | LastName

<标题> 许可

PermissionId | CompanyId | Permission

<标题> EmployeePermission h1> mployeePermissionId | PermissionId | EmployeeId

和POCO如下:

[Table("Employee")]
public class Employee
{
    public int EmployeeId { get; set; }
    public int CompanyId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Company Company { get; set; }
    public List<Permission> Permissions { get; set; }
}

我希望能够加载公司和权限作为雇员的属性。我可以让公司加载以下代码:

var employee = _context.Employees
            .Where(u => u.EmpoyeeId == 1234)
            .Include(u => u.Company)
            .FirstOrDefault();

不知道如何加载Permission集合

实体框架4.1 POCO -多对多加载

您需要更改数据库结构来实现这一点。

您的EmployeePermission表应该只包含2个外键列。通过这样做,EF将透明地管理链接表,您可以在Employee类中拥有Permissions属性。

更改Employee类定义,使导航属性为虚拟。

[Table("Employee")]
public class Employee
{
    public int EmployeeId { get; set; }
    public int CompanyId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual Company Company { get; set; }
    public virtual ICollection<Permission> Permissions { get; set; }
}

然后可以加载Permissions

var employee = _context.Employees
            .Where(u => u.EmpoyeeId == 1234)
            .Include(u => u.Company).Include(u => u.Permissions)
            .FirstOrDefault();

对于多对多关系

public class Employee
{
 public int EmployeeId { get; set; }
    public int CompanyId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual Company Company { get; set; }
    public virtual ICollection<Permission> Permissions { get; set; }
}
public class  Permission {
public virtual ICollection<Employee> Employee{ get; set; }
}

用Employee_Id和Permission_Id创建一个新的表EmployeePermission