c# - 如何使用 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);
还有比这更多的内容。当然,这会导致 EF Core 3.0 在 SQL 查询中生成许多连接,这意味着它需要永远执行(检索 200 条记录需要 25 多秒)。
我尝试使用格式.Include(x => x.LocalStats.StatType1)
而不是 Include 和 ThenInclude,但结果是一样的。
有什么方法可以提高效率吗?文档建议:
具有大量
Include
运算符的 LINQ 查询可能需要分解为多个单独的 LINQ 查询,以避免笛卡尔爆炸问题。
但我没有看到任何关于如何实际实现这一点的解释。
解决方案
最终我最终手动编写了 SQL,我找不到使生成的 SQL 足够高效的方法。还可以考虑考虑优化数据库,例如添加聚集索引。这大大减少了数据库时间。
推荐阅读
- bash - Docker bash 完成无法在我的 Mac 上运行
- java - 相同的输入,相同的输出,但不同的结果(CodeForces)
- flutter - 前导图标的颤振标题置换
- google-bigquery - BigQuery 上的模糊匹配电子邮件
- c# - 如何检查 POS 打印机状态
- javascript - 水平拆分窗格 vue 组件未在电子中调整大小
- vue.js - 我的图像标签内的 vue 插值作为 src:" {{ image }}"
- javascript - 如何使用 lodash 在 SQL IN 子句等条件下过滤数组?
- git - 没有“比较和拉取请求”按钮/来自错误用户的推送
- python - 如何在 for 循环(if else 语句)中打印数据间隔?Python 问题