如何让Linq-to-Entities提供商真正执行GROUP BY
?无论我做什么,它总是生成比实际GROUP BY
慢得多的SQL。例如:
var foo = (from x in Context.AccountQuantities
where x.AccountID == 27777
group x by x.StartDate
into groups
select new
{
groups.FirstOrDefault().StartDate,
Quantity = groups.Max(y => y.Quantity)
}).ToList();
转换为:
SELECT
1 AS [C1],
[Project4].[C1] AS [C2],
[Project4].[C2] AS [C3]
FROM ( SELECT
[Project3].[C1] AS [C1],
(SELECT
MAX([Extent3].[Quantity]) AS [A1]
FROM [dbo].[AccountQuantities] AS [Extent3]
WHERE (27777 = [Extent3].[AccountID]) AND ([Project3].[StartDate] = [Extent3].[StartDate])) AS [C2]
FROM ( SELECT
[Distinct1].[StartDate] AS [StartDate],
(SELECT TOP (1)
[Extent2].[StartDate] AS [StartDate]
FROM [dbo].[AccountQuantities] AS [Extent2]
WHERE (27777 = [Extent2].[AccountID]) AND ([Distinct1].[StartDate] = [Extent2].[StartDate])) AS [C1]
FROM ( SELECT DISTINCT
[Extent1].[StartDate] AS [StartDate]
FROM [dbo].[AccountQuantities] AS [Extent1]
WHERE 27777 = [Extent1].[AccountID]
) AS [Distinct1]
) AS [Project3]
) AS [Project4]
我怎样才能让它执行此操作呢?
SELECT
AccountQuantities.StartDate,
MAX(AccountQuantities.Quantity)
FROM AccountQuantities
WHERE AccountID=27777
GROUP BY StartDate
再次注意,在执行的内容中缺少任何GROUP BY
。我很好地利用EF非理想地优化了一些东西,但是这个数字要慢一些,我找不到任何方法来说服它真正做GROUP BY
,这对我们来说是个主要问题!
答案 0 :(得分:2)
使用groups.Key而不是groups.FirstOrDefault()。StartDate
var foo = (from x in Context.AccountQuantities
where x.AccountID == 27777
group x by x.StartDate
into groups
select new
{
groups.Key,
Quantity = groups.Max(y => y.Quantity)
}).ToList();