2011-11-10 72 views
2

我有以下4個表(簡化了這個問題):實體框架4.1 POCO - 多到許多裝載


公司

CompanyId |名稱

僱員

EmpoyeeId |公司ID |名字|姓氏

權限

PermissionId |公司ID | Permission

EmployeePermission

EmployeePermissionId | PermissionId |僱員


而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(); 

不知道如何加載權限的集合,雖然。

回答

5

您需要對數據庫結構進行更改才能實現此目的。

您的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(); 
0

爲多對多的關係

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