c# - EntityFramework Group by 不包含在 SQL 语句中

标签 c# sql linq entity-framework group-by

我正在尝试创建与此类似的查询:

select randomId 
from myView
where ...
group by randomId

注意:EF 不支持 distinct 所以我想通过 group by 来解决它的不足(或者我认为如此)

randomId is numeric

Entity Framework V.6.0.2

这在 < 1 秒的查询中给了我预期的结果

当尝试对 EF 执行相同操作时,我遇到了一些问题。

如果我执行与此类似的 LINQ:

context.myView
.Where(...)
.GroupBy(mt => mt.randomId)
.Select({ Id = group.Key, Count = group.Count() } )

我会得到类似的结果,但强制计数并使查询 > 6 秒

SQL EF 生成的是这样的:

SELECT 
1 AS [C1],
[GroupBy1].[K1] AS [randomId],
[GroupBy1].[A1] AS [C2]
FROM ( 
SELECT 
     [Extent1].[randomId] AS [K1],
     COUNT(1) AS [A1]
     FROM [dbo].[myView] AS [Extent1]
     WHERE (...)
     GROUP BY [Extent1].[randomId]
)  AS [GroupBy1]

但是,如果查询将计数注释掉,它将返回到 < 1 秒

如果我将 Select 更改为:

.Select({ Id = group.Key} )

我将获得 SQL 查询中没有 group by 语句且没有任何 Distinct 的所有行:

SELECT 
[Extent1].[anotherField] AS [anotherField], -- 'this field got included automatically on this query and I dont know why, it doesnt affect outcome when removed in SQL server'
[Extent1].[randomId] AS [randomId]
FROM [dbo].[myView] AS [Extent1]
WHERE (...)

其他失败的尝试:

query.GroupBy(x => x.randomId).Select(group => group.FirstOrDefault());

生成的查询如下:

SELECT 
    [Limit1].ALL FIELDS,...
    FROM  (SELECT 
        [Extent1].[randomId] AS [randomId]
        FROM [dbo].[myView] AS [Extent1]
        WHERE (...) AS [Project1]
    OUTER APPLY  (SELECT TOP (1) 
        [Extent2].ALL FIELDS,...
        FROM [dbo].[myView] AS [Extent2]
        WHERE (...) AS [Limit1] -- same as the where above

此查询执行得相当糟糕,但仍设法返回 where 子句的所有 ID。

有没有人知道如何在没有像计数这样的聚合函数的情况下强制使用分组依据

在 SQL 中它可以工作,但我也有 distinct 关键字......

干杯, J

最佳答案

var query = from p in TableName 
        select new {Id = p.ColumnNameId};
var distinctItems = query.Distinct().ToList();

这是 linq 查询,但您也应该能够从 EF dbset 编写等效的查询。如果您有问题,请告诉我。

干杯!

关于c# - EntityFramework Group by 不包含在 SQL 语句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23216971/

相关文章:

c# - 我可以为属性使用集合初始值设定项吗?

php - ORA-06550 必须声明标识符

SQL Server 列比较,包括 Null/Not Null

.net - 我可以依赖 LINQ ToArray() 总是返回一个新实例吗?

c# - 结合其他对象列表构建新的对象列表

c# - 在 LINQ 中转换为 int 不起作用?

c# - .NET 4 中的 URL 重写?

c# - 反序列化动态 JSON 响应

要从 1 小时前选择的 Sql 查询?

c# - 为什么这个额外的连接会增加查询的数量?