EntityFramework Group不包含在SQL语句中

时间:2014-04-22 10:29:58

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

我尝试创建类似于此的查询:

select randomId 
from myView
where ...
group by randomId

注意:EF不支持 distinct ,所以我想通过来解决组的缺乏(或者我认为)< / p>

  

randomId是数字

     

实体框架V.6.0.2

这给了我预期的结果&lt; 1秒查询

当试图用EF做同样的事情时,我遇到了一些问题。

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

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

我会得到一些相同的结果,但强制计数并进行查询&gt; 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]

但是,如果查询已将该计数注释掉,那么它将返回&lt; 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关键字......

干杯, Ĵ

1 个答案:

答案 0 :(得分:0)

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

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

干杯!