实体框架方法组包含不起作用

时间:2016-01-20 16:07:05

标签: c# entity-framework linq eager-loading method-group

我在EF中使用方法组加载相关实体时遇到了一些麻烦。

在简单查询中,加载相关实体可与std::deque一起使用。

例如:

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(或该集合中的任何其他项目)的值相同。
问题是我不需要将Employee和Project作为此动态对象 result3 中的单独属性。

如何在返回result2的方法中使用Employee和Project? :)

1 个答案:

答案 0 :(得分:2)

我很少使用查询语法,并且我从未遇到过使用.Include(typeof(..)。Name)语法的人,请尝试以下操作:

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;才能发挥作用。