C# 对于空组,LINQ计数返回1而不是零

C# 对于空组,LINQ计数返回1而不是零,c#,entity-framework,linq,group-by,C#,Entity Framework,Linq,Group By,我有一个SQL查询: SELECT oy.ownerId, oy.Year, COUNT(doc.Id) as docCount FROM aavabruf.owneryears oy left join vastdocuments doc on oy.ownerId = doc.Ownerid and oy.Year = doc.Year group by oy.ownerid, oy.year order by docCount 它将OwnerId、年份对的docCount显示为零

我有一个SQL查询:

SELECT oy.ownerId, oy.Year,  COUNT(doc.Id) as docCount FROM aavabruf.owneryears oy 
left join vastdocuments doc
on oy.ownerId = doc.Ownerid and  oy.Year =  doc.Year
group by oy.ownerid, oy.year
order by docCount
它将OwnerId、年份对的docCount显示为零,这些对在文档表中没有文档匹配项

我尝试使用建议的左外连接解决方案对LINQ执行相同的操作:

from oy in OwnerYears
join doc in VaStDocuments on new {oy.OwnerId, oy.Year} equals new {doc.OwnerId , doc.Year} into docS
from docIfNull in docS.DefaultIfEmpty()
group oy by new {oy.OwnerId, oy.Year} into g
orderby g.Count() ascending
select new { OwnerId = g.Key.OwnerId,  Year = g.Key.Year, docCount = g.Count()}
但是,对于OwnerId,文档表中不存在的年份组,我将docCount设置为1,而不是零。如果我移除

来自docS.DefaultIfEmpty()中的docIfNull

行“空”组将完全不显示

如何像在SQL查询中一样将计数设为零?我尝试了以下方法:

Count=docIfNull==null?0:g.计数()

但是在这种情况下,我得到一个错误:

当前上下文中不存在名称“docIfNull”


最简单的方法是计算非空值:

g.Count(x => x != null)
我建议在
选择之后移动订购,这样您就可以避免重复自己的操作:

select new { g.Key.OwnerId, g.Key.Year, DocCount = g.Count(x => x != null) } into result
orderby result.DocCount
select result
但是,我注意到目前您根本没有使用
docIfNull
。。。所以我怀疑你的加入并不是你想要的。也许你应该使用

group docIfNull by new { oy.OwnerId, oy.Year } into g

最简单的方法是计算非空值:

g.Count(x => x != null)
我建议在
选择之后移动订购,这样您就可以避免重复自己的操作:

select new { g.Key.OwnerId, g.Key.Year, DocCount = g.Count(x => x != null) } into result
orderby result.DocCount
select result
但是,我注意到目前您根本没有使用
docIfNull
。。。所以我怀疑你的加入并不是你想要的。也许你应该使用

group docIfNull by new { oy.OwnerId, oy.Year } into g

SQL
COUNT
函数忽略
NULL
值,而LINQ
COUNT
函数不带谓词对一切进行计数,包括
NULL
s

通过像这样使用
Count
的谓词版本,可以在LINQ中获得相同的结果(注意
组docIfNull
,因此
g
元素的类型将与
docIfNull
相同):

(let
子句只是重复使用
orderby
select
中的表达式)

然而,在LINQ中,您还有另一个选择-如果
(OwnerId,Year)
内部的组合
OwnerYears
看起来是唯一的,而不是
左外连接
模式,然后是
分组方式
计数
过滤空值,您可以使用带有常规
计数
调用的简单运算符:

from oy in OwnerYears
join doc in VaStDocuments on new { oy.OwnerId, oy.Year } equals new { doc.OwnerId, doc.Year } into docs
let docCount = docs.Count()
orderby docCount ascending
select new { OwnerId = oy.OwnerId,  Year = oy.Year, docCount = docCount }

SQL
COUNT
函数忽略
NULL
值,而LINQ
COUNT
函数不带谓词对所有内容进行计数,包括
NULL
s

通过像这样使用
Count
的谓词版本,可以在LINQ中获得相同的结果(注意
组docIfNull
,因此
g
元素的类型将与
docIfNull
相同):

(let
子句只是重复使用
orderby
select
中的表达式)

然而,在LINQ中,您还有另一个选择-如果
(OwnerId,Year)
内部的组合
OwnerYears
看起来是唯一的,而不是
左外连接
模式,然后是
分组方式
计数
过滤空值,您可以使用带有常规
计数
调用的简单运算符:

from oy in OwnerYears
join doc in VaStDocuments on new { oy.OwnerId, oy.Year } equals new { doc.OwnerId, doc.Year } into docs
let docCount = docs.Count()
orderby docCount ascending
select new { OwnerId = oy.OwnerId,  Year = oy.Year, docCount = docCount }

跟踪查询并将其作为tsql在数据库中检查?跟踪查询并将其作为tsql在数据库中检查?