我正在使用Entity Framework Core 2.1.4,并且从C#编写了一个基本示例查询,如下所示。
var myList = context.HastaAdres.OrderBy(p => p.ID).Take(20).GroupBy(p => p.IlKodu).Select(d => d.FirstOrDefault()).Select(p => p.ID).ToList();
但是在SQL事件探查器中,运行如下代码。 SQL中没有分组依据,与经典实体框架有很大不同。因此,结果也不同。结果,我只需要一列。但是首先查询,返回所有列。行数也不同于第二个查询。
实体框架核心生成的SQL
SELECT [t].[ID], [t].[IlKodu], [t].[AcikAdres], [t].[BucakAdi], [t].[BucakKodu], [t].[BulvarKodu], [t].[CaddeKodu], [t].[CreatedBy], [t].[CreatedDate]
FROM (
SELECT TOP(20) [p].[ID], [p].[IlKodu], [p].[AcikAdres], [p].[BucakAdi], [p].[BucakKodu], [p].[BulvarKodu], [p].[CaddeKodu], [p].[CreatedBy], [p].[CreatedDate]
FROM [Ortak].[HastaAdres] AS [p]
ORDER BY [p].[ID]
) AS [t]
ORDER BY [t].[IlKodu]
当我在Entity Framework中尝试此方法时,它会生成完美的代码。
由实体框架生成的SQL
SELECT
(SELECT TOP (1)
[Limit2].[ID] AS [ID]
FROM ( SELECT TOP (20) [Extent2].[ID] AS [ID], [Extent2].[IlKodu] AS [IlKodu]
FROM [Ortak].[HastaAdres] AS [Extent2]
ORDER BY [Extent2].[ID] ASC
) AS [Limit2]
WHERE ([Distinct1].[IlKodu] = [Limit2].[IlKodu]) OR (([Distinct1].[IlKodu] IS NULL) AND ([Limit2].[IlKodu] IS NULL))) AS [C1]
FROM ( SELECT DISTINCT [distinct].[IlKodu] AS [IlKodu]
FROM ( SELECT TOP (20)
[Extent1].[IlKodu] AS [IlKodu]
FROM [Ortak].[HastaAdres] AS [Extent1]
ORDER BY [Extent1].[ID] ASC
) AS [distinct]
) AS [Distinct1]
这种情况可能是什么原因?
答案 0 :(得分:1)
我了解到EF Core不支持数据库级别Group By和take元素。但是,在EF Core 2.1中,它支持对数据库级别的按总和,最小值,最大值,平均值进行分组。(您可以从此链接https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.1#linq-groupby-translation中看到@jpgrassi的评论)
因此,我将查询代码更改为采用最小值,然后从数据库中获取该行。因此,这解决了我的问题。但是,我希望Microsoft最近一次在数据库级别支持分组方式。