如何使用 EF Core 3.0 提高多个包含的效率

Arc*_*Arc 6 c# linq asp.net-core ef-core-3.0

我有一个多级查询,包括:

var itemsToday = DatabaseContext.Items
                .Where(f => f.StartTime > DateTime.Today && f.StartTime < DateTime.Today.AddDays(1))
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType1)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType2)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType3)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType4)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType5)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType6)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType7)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType8)
                .Include(x => x.LocalStats).ThenInclude(x=>x.StatType9)
                .Include(x => x.LocalDetails)
...
                .OrderBy(f=>f.SomeOrderingCriterion);
Run Code Online (Sandbox Code Playgroud)

还有比这更多的包含。当然,这会导致 EF Core 3.0在 SQL 查询中生成许多连接,这意味着执行需要很长时间(25 秒以上才能检索 200 条记录)。

我曾尝试使用格式.Include(x => x.LocalStats.StatType1)而不是 Include 和 ThenInclude,但结果是一样的。

有什么方法可以使这更有效吗?文档建议:

具有大量Include运算符的LINQ 查询可能需要分解为多个单独的 LINQ 查询,以避免笛卡尔爆炸问题。

但是我没有看到有关如何实际完成此操作的任何解释。

Arc*_*Arc 0

最终我最终手动编写了 SQL,我找不到一种方法使生成的 SQL 足够高效。还可以考虑优化数据库,例如添加聚集索引。这大大减少了数据库时间。