在版本2.1之前,在EF Core中,GroupBy 表达式运算符总是在内存中进行计算的。现在支持在大多数情况下将其转换为SQL GROUP BY子句。
var query = context.Orders .GroupBy(o => new { o.CustomerId, o.EmployeeId }) .Select(g => new { g.Key.CustomerId, g.Key.EmployeeId, Sum = g.Sum(o => o.Amount), Min = g.Min(o => o.Amount), Max = g.Max(o => o.Amount), Avg = g.Average(o => Amount) });相应的SQL解析如下所示:
SELECT [o].[CustomerId], [o].[EmployeeId], SUM([o].[Amount]), MIN([o].[Amount]), MAX([o].[Amount]), AVG([o].[Amount]) FROM [Orders] AS [o] GROUP BY [o].[CustomerId], [o].[EmployeeId];