Entity Framework 4.1 POCO - 多对多加载
我有以下 4 个表(针对此问题进行了简化
)
:姓名
员工
EmpoyeeId |公司编号 |名字 |姓氏
权限
PermissionId |公司编号 |权限
EmployeePermission
EmployeePermissionId |权限 ID | 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; }
}
我希望能够加载公司和权限作为 Employee 的属性。我可以让公司加载以下代码:
var employee = _context.Employees
.Where(u => u.EmpoyeeId == 1234)
.Include(u => u.Company)
.FirstOrDefault();
但不确定如何加载权限集合。
I have the following 4 tables (simplified for this question):
Company
CompanyId | Name
Employee
EmpoyeeId | CompanyId | FirstName | LastName
Permission
PermissionId | CompanyId | Permission
EmployeePermission
EmployeePermissionId | PermissionId | EmployeeId
And the POCO as below:
[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; }
}
I want to be able to load the company and permissions as properties of Employee. I can get the Company to load with the following code:
var employee = _context.Employees
.Where(u => u.EmpoyeeId == 1234)
.Include(u => u.Company)
.FirstOrDefault();
Not sure how to load the collection of Permission though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要更改数据库结构才能实现这一目标。
您的
EmployeePermission
表应仅包含 2 个外键列。通过这样做,EF 将透明地管理链接表,并且您可以在Employee
类中拥有Permissions
属性。更改
Employee
类定义以使导航属性变为虚拟。然后你可以立即加载
Permissions
You need to make changes to the database structure to achieve that.
Your
EmployeePermission
table should contain only 2 foreign key columns. By doing so EF will manage the link table transparently and you can havePermissions
property inEmployee
class.Change the
Employee
class definition to make the navigational properties virtual.Then you can eager load
Permissions
对于多对多关系
,使用 Employee_Id 和 Permission_Id 创建新表 EmployeePermission
for many to many relationship
that create a new table EmployeePermission with Employee_Id and Permission_Id