实体框架方法组包含不起作用
本文关键字:包含 不起作用 方法 框架 实体 | 更新日期: 2023-09-27 18:31:14
我在EF中使用方法组加载相关实体时遇到了一些麻烦。
在简单查询中,相关实体的加载可以正常工作Include
。
例如:
var result =
Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null && myTeam.Contains(x.EmployeeID))
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
.OrderByDescending(x => x.SubmitedDate);
工作完美,并加载项目和员工
但在下一个查询中不加载项目和员工
var result2 = from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select item;
我试图做这样的改变:select new { item, item.Employee, item.Project };
var result3 = from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
.Include(typeof(Project).Name)
.Include(typeof(Employee).Name)
.Include(typeof(EmployeeDetails).Name)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select new { item, item.Employee, item.Project };
之后,result3[0].Employee
有一个值,与result3[0].Project
(或该集合中的任何其他项目)相同。
问题是我不需要将员工和项目作为此动态对象 result3 中的单独属性。
如何在返回 result2 的方法中包含员工和项目? :)
我很少使用查询语法,也从未遇到过使用 .包括(类型(..).名称)语法,请尝试以下操作:
var result2 = (from item in Repository.Query<TimeState>(x => x.Accepted == 0 && x.ProjectID != null)
let projectId = (int)item.ProjectID
let isA = projectsIds.Contains(projectId) && item.Employee.EmployeeDetails.SuperiorID == id
let isB = item.Project.ManagerID == id && employeesTeam.Contains(item.EmployeeID)
where isA || isB
orderby item.SubmitedDate descending
select item)
.Include(i=>i.Projects)
.Include(i=>i.Employees)
.Include(i=>i.EmployeeDetails);
您可能还需要包含using System.Data.Entity;
才能正常工作。