我需要一个简单的Linq查询,以从外键表(Dept)获取员工记录和计数。以下查询不起作用
System.InvalidOperationException:‘LINQ表达式'GroupByShaperExpression: KeySelector: q.DeptId,ElementSelector:new .Select(x => x.EmpName) .First()’无法翻译。可以用可以翻译的表单重写查询,或者通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用,显式地切换到客户端计算。更多信息请参见https://go.microsoft.com/fwlink/?linkid=2101038。
var query = from h in context.Employee
join p in context.Dept on h.EmpId equals p.DeptId
select new
{
h.EmpId,
h.EmpName,
h.Salary,
p.DeptId
};
var groupQuery = from q in query
group q by q.DeptId into g
select new
{
DeptCount = g.Count(),
Empname=g.Select(s=>s.EmpName).First(),
Salary = g.Select(s => s.Salary).First(),
EmpId = g.Select(s => s.EmpId).First()
};
return groupQuery.ToList();
表scehma:
发布于 2022-03-24 01:13:14
作为sql,您应该对希望看到的每个未聚合的字段进行分组。
试试这个:
var query = from h in context.Employee
join p in context.Dept on h.EmpId equals p.DeptId
select new
{
h.EmpId,
h.EmpName,
h.Salary,
p.DeptId
};
var groupQuery = from q in query
group q by new {EmpId= q.EmpId, EmpName = q.EmpName, Salary = q.Salary} into g
select new
{
DeptCount = g.Count(),
Empname=g.Key.EmpName,
Salary = g.Key.Salary,
EmpId = g.Key.EmpId
};
return groupQuery.ToList();
你也可以用这种方式做同样的事情。
var query = from h in context.Employee
join p in context.Dept on h.EmpId equals p.DeptId
group new {h, p} by h into g
select new
{
DeptCount = g.Count(),
Empname=g.Key.EmpName,
Salary = g.Key.Salary,
EmpId = g.Key.EmpId
};
如果员工没有部门,您也应该注意,并在join上使用DefaultIfEmpty:
var query = from h in context.Employee
join p in context.Dept on h.EmpId equals p.DeptId into xp
from jp in xp.DefaultIfEmpty()
group new {h, jp} by h into g
select new
{
DeptCount = g.Count(),
Empname = g.Key.EmpName,
Salary = g.Key.Salary,
EmpId = g.Key.EmpId
};
https://stackoverflow.com/questions/71598694
复制