简体   繁体   中英

What is fastest way to get count with other fields using LINQ - Entity Framework

I am fetching employee count for each result:

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

Please suggest faster and more efficient method to fetch the data.

Since the employee-count-per-department is a fairly simple query, which would also be redundant if you execute it for every employee, I would first query the employee-count-per-department, and use that result afterwards in your current query.

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

I must say that I find it confusing that your Employees table contains a column DepartmentId and Department contains a column EmployeeId . Seems like two foreign keys connecting the same table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM