简体   繁体   English

LINQ to Entities group by和Count()

[英]LINQ to Entities group by and Count()

I have the following LINQ-to-Entities query 我有以下LINQ到实体查询

from r in ctx.Rs
join p in ctx.Ps on r.RK equals p.RK
group r by r.QK into gr
select new { QK = (int)gr.Key, Num = gr.Count() }

that runs against this schema 针对此架构运行

Table P  Table R   Table Q
 PK*
 RK ----> RK*
 Text     QK ------> QK*
          Text       Text

and gives this message if there is any record in Q with no corresponding record in P: "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type." 如果Q中有任何记录,并且P中没有相应的记录,则给出此消息:“转换为值类型'Int32'失败,因为具体化值为null。结果类型的泛型参数或查询必须使用可空类型。 “

The problem is the gr.Count() in the last line, but I cannot find a solution. 问题是最后一行中的gr.Count(),但我找不到解决方案。 I have tried to test gr for null, but cannot find a way that works. 我试图测试gr为null,但找不到有效的方法。

I have seen a number of solutions to a similar problem using Sum() instead of Count(), but I have not been able to adapt them to my problem. 我已经看到使用Sum()而不是Count()的类似问题的一些解决方案,但我无法使它们适应我的问题。

I tried changing my query to look like the one in Group and Count in Linq issue , but I just got a different message. 我尝试将查询更改为在Linq问题中的Group和Count中的查询,但我只是得到了不同的消息。

I also looked at Group and Count in Entity Framework (and a number of others) but the problem is different. 我还查看了实体框架中的Group and Count (以及其他一些),但问题不同。

group Key can't be null 组键不能为空

var results = ctx.Rs.Where(r => r.QK != null)
    .GroupBy(r => r.QK)
    .Select(gr => new { Key = (int)gr.Key, Count = gr.Count() }
    .ToList();

PS. PS。

  1. Mostly, You don't need 'JOIN' syntax in Entity Framework. 大多数情况下,您不需要Entity Framework中的“JOIN”语法。 see: Loading Related Entities 请参阅: 加载相关实体

  2. Writing descriptive-meaningful variable names would significantly improve Your codes and make it understandable. 编写具有描述性的有意义的变量名称可以显着改善您的代码并使其易于理解。 Readability does matter in real world production. 可读性在现实生产中很重要。

I'm having trouble reading your format. 我在阅读你的格式时遇到了麻烦。 But can you try: 但是你可以尝试:

from r in ctx.Rs
join p in ctx.Ps.DefaultIfEmpty() on r.RK equals p.RK
group r by r.QK into gr
select new { QK = (int)gr.Key, Num = gr.Count(x => x.RK != null) }

With DefaultIfEmpty and x => x.RK != null being the changes. 使用DefaultIfEmptyx => x.RK != null作为更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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