缓慢的 EF 查询分组数据 Month/Year

Slow EF query grouping data by Month/Year

我有大约 100 万条记录的记录集。我正在尝试查询记录以报告月度数据。

以下 MySQL 查询在大约 0.3 秒内执行

SELECT SUM(total), MONTH(create_datetime), YEAR(create_datetime) 
FROM orders GROUP BY MONTH(create_datetime), YEAR(create_datetime)

但是我想不出一个 entity framework lambda 表达式可以像

一样快速执行

我想出的唯一有效的说法是

var monthlySales = db.Orders
                     .Select(c => new
                     {
                         Total = c.Total,
                         CreateDateTime = c.CreateDateTime
                     })
                     .GroupBy(c => new { c.CreateDateTime.Year, c.CreateDateTime.Month })
                     .Select(c => new
                     {
                         CreateDateTime = c.FirstOrDefault().CreateDateTime,
                         Total = c.Sum(d => d.Total)
                     })
                     .OrderBy(c => c.CreateDateTime)
                     .ToList();

但是速度慢得可怕。

如何让这个查询像直接在 MySQL

中一样快速执行

当您在查询中间执行“.ToList()”时(在进行分组之前),EF 将有效地查询内存中数据库中的所有订单,然后在 C# 中进行分组。根据您 table 中的数据量,这可能需要一段时间,我认为这就是您的查询如此缓慢的原因。

尝试重写仅包含 1 个枚举结果的表达式(ToList、ToArray、AsEnumerable)的查询

试试这个:

var monthlySales = from c in db.Orders
                   group c by new { y = c.CreateDateTime.Year, m = c.CreateDateTime.Month } into g
                   select new {
                       Total = c.Sum(t => t.Total),
                       Year = g.Key.y,
                       Month = g.Key.m }).ToList();

我遇到了这个执行速度很快的设置

            var monthlySales = db.Orders
                 .GroupBy(c => new { Year = c.CreateDateTime.Year, Month = c.CreateDateTime.Month })
                 .Select(c => new
                 {
                     Month = c.Key.Month,
                     Year = c.Key.Year,
                     Total = c.Sum(d => d.Total)
                 })
                 .OrderByDescending(a => a.Year)
                 .ThenByDescending(a => a.Month)
                 .ToList();