分组后的LINQ to Entities,COUNT和WHERE不起作用
Posted
技术标签:
【中文标题】分组后的LINQ to Entities,COUNT和WHERE不起作用【英文标题】:LINQ to Entities after group by, COUNT and WHERE not working 【发布时间】:2021-10-13 09:36:53 【问题描述】:我对 mysql DB 有以下 LINQ-to-Entities 查询
var data = (from agent in db.User
join agentrole in db.UserRole.DefaultIfEmpty() on agent.Id equals agentrole.UserId
join role in db.Role.DefaultIfEmpty() on agentrole.RoleId equals role.Id
join department in db.Department.DefaultIfEmpty() on role.DepartmentId equals department.Id
join client in db.Client.DefaultIfEmpty() on agent.Id equals client.AssignedUserId
join aggclient in db.AggClient.DefaultIfEmpty() on client.Id equals aggclient.ClientId
group new agent, department, aggclient by agent.Id into grp
select new
grp.Key,
agentName = grp.Max(a => a.agent.FirstName + " " + a.agent.LastName),
departmentNames = "",
newDepositorsCount = 0,
FTDSum = grp.Sum(a => a.aggclient.FirstDepositAmountEuro),
depcount =grp.Count(a => a.department != null),
aggclientfilter = grp.Where(a => a.aggclient != null && a.aggclient.FirstDepositAmount>0).Sum(a => a.aggclient.FirstDepositAmount)
);
在当前查询中,最后两个操作不起作用。 实体无法解析 count 和 where 操作。
【问题讨论】:
您应该使用导航属性,而不是连接。然后你就不需要 GroupBy 并且一切都会变得更容易编码。如果您需要帮助,请展示类模型并提及您的 EF 版本。 【参考方案1】:将select clause
更改为:
select new
grp.Key,
agentName = grp.agent.Max(a => a.FirstName + " " + a.LastName),
departmentNames = "",
newDepositorsCount = 0,
FTDSum = grp.aggclient.Sum(a => a.FirstDepositAmountEuro),
depcount = grp.department.Count(),
aggclientfilter = grp.aggclient.Where(a => a.FirstDepositAmount>0).Sum(a => a.FirstDepositAmount)
);
【讨论】:
【参考方案2】:我假设你不使用 EF Core 5.x,因为它支持过滤计数。
此类 LINQ 查询没有正确转换为 SQL 的问题。但是有些技巧可以返回所需的结果。还更正了错误的 LEFT 连接。
var data =
from agent in db.User
join agentrole in db.UserRole on agent.Id equals agentrole.UserId into ga
from agentrole in ga.DefaultIfEmpty()
join role in db.Role on agentrole.RoleId equals role.Id into gr
from role in gr.DefaultIfEmpty()
join department in db.Department on role.DepartmentId equals department.Id into dg
from department in dg.DefaultIfEmpty()
join client in db.Client on agent.Id equals client.AssignedUserId
join aggclient in db.AggClient on client.Id equals aggclient.ClientId into acg
from aggclient in acg.DefaultIfEmpty()
group new agent, department, aggclient by agent.Id into grp
select new
grp.Key,
agentName = grp.Max(a => a.agent.FirstName + " " + a.agent.LastName),
departmentNames = "",
newDepositorsCount = 0,
FTDSum = grp.Sum(a => a.aggclient.FirstDepositAmountEuro),
depcount = grp.Sum(a => a.department != null ? 1 : 0),
aggclientfilter = grp.Sum(a => a.aggclient.FirstDepositAmount > 0 ? a.aggclient.FirstDepositAmount : 0)
;
【讨论】:
以上是关于分组后的LINQ to Entities,COUNT和WHERE不起作用的主要内容,如果未能解决你的问题,请参考以下文章
为啥 LINQ-to-Entities 将此查询放在子选择中?
Linq-to-Entities:带有 WHERE 子句和投影的 LEFT OUTER JOIN