[英]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. 由于每个部门的employee-count是一个相当简单的查询,如果你为每个员工执行它,这也是多余的,我首先会查询每个部门的employee-count,然后在当前查询中使用该结果。
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
. 我必须说,我发现令人困惑的是,您的
Employees
表包含一个DepartmentId
列, 而 Department
包含一列EmployeeId
。 Seems like two foreign keys connecting the same table. 好像连接同一个表的两个外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.