C# LINQ to Entities group by 和 Count()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14472106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:55:05  来源:igfitidea点击:

LINQ to Entities group by and Count()

c#linqentity-frameworkcountgroup-by

提问by Jim S

I have the following LINQ-to-Entities query

我有以下 LINQ-to-Entities 查询

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' 失败,因为具体化值为空。结果类型的泛型参数或查询必须使用可空类型。 ”

The problem is the gr.Count() in the last line, but I cannot find a solution. I have tried to test gr for null, but cannot find a way that works.

问题是最后一行的 gr.Count(),但我找不到解决方案。我试图测试 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 和 Count,但问题有所不同。

回答by Joe

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 DefaultIfEmptyand x => x.RK != nullbeing the changes.

随着DefaultIfEmptyx => x.RK != null正在发生变化。

回答by aifarfa

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.

附注。

  1. Mostly, You don't need 'JOIN' syntax in Entity Framework. 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.

  1. 大多数情况下,您不需要实体框架中的“JOIN”语法。请参阅:加载相关实体

  2. 编写具有描述性意义的变量名称将显着改进您的代码并使其易于理解。可读性在现实世界的生产中很重要。