使用LINQ - Entity Framework获取其他字段的最快方法是什么

时间:2016-09-07 05:55:05

标签: c# entity-framework

我正在获取每个结果的员工数:

var query = (from Department dept in database.Department
             join emp in database.Employees on dept.EmployeeId equals emp.EmployeeId
             where dept.IOfficeId == officeId 
             select new EmployeeData
                    {
                        FullName = emp.Name,
                        EmployeeId = dept.EmployeeId,
                        DepartmentName = dept.Name,
                        EmployeeCount = 
                             (from Employees emp_count in database.Employees 
                              where emp_count.DepartmentId == dept.DepartmentId).Count()
                    });

请建议更快,更有效的方法来获取数据。

1 个答案:

答案 0 :(得分:0)

由于employee-count-per-department是一个相当简单的查询,如果你为每个员工执行它,这也是多余的,我首先会查询employee-count-per-department,然后使用该结果您当前的查询。

var departmentEmployeeCount = database.Employees
    .GroupBy(x => x.DepartmentId)
    .Select(x => new { DepartmentId = x.Key, Count = x.Count() })
    .ToArray();

var query = (from Department dept in database.Department
             join emp in database.Employees on dept.EmployeeId equals emp.EmployeeId
             where dept.IOfficeId == officeId
             select new {
                emp.Name,
                dept.EmployeeId,
                dept.Name,
                dept.DepartmentId
             }
            )
            .AsEnumerable()
            .Select(x => new EmployeeData {
                FullName = x.Name,
                EmployeeId = x.EmployeeId,
                DepartmentName = x.Name,
                EmployeeCount = departmentEmployeeCount
                    .Where(z => z.DepartmentId == x.DepartmentId)
                    .Select(x => x.Count)
                    .FirstOrDefault()
                }
            );

我必须说,我发现您的Employees表包含列DepartmentId Department包含列EmployeeId,这让我感到困惑。好像连接同一个表的两个外键。