如何使用 EF Core 3.0 使多个包含更高效
How to make multiple includes more efficient with 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 查询中生成 many 联接,这意味着它需要永远执行(检索 200 条记录需要 25 秒以上)。
我试过使用格式 .Include(x => x.LocalStats.StatType1)
而不是 Include 和 ThenInclude,但结果是一样的。
有什么方法可以提高效率吗?文档建议:
LINQ queries with an exceedingly high number of Include
operators may need to be broken down into multiple separate LINQ queries in order to avoid the cartesian explosion problem.
但我没有看到任何关于如何实际完成此操作的解释。
您应该考虑延迟加载此查询。
https://docs.microsoft.com/en-us/ef/core/querying/related-data
最终我手动编写了 SQL,我找不到使生成的 SQL 足够高效的方法。还要考虑优化数据库,例如添加聚簇索引。这大大减少了数据库时间。
我有一个包含许多多级的查询:
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 查询中生成 many 联接,这意味着它需要永远执行(检索 200 条记录需要 25 秒以上)。
我试过使用格式 .Include(x => x.LocalStats.StatType1)
而不是 Include 和 ThenInclude,但结果是一样的。
有什么方法可以提高效率吗?文档建议:
LINQ queries with an exceedingly high number of
Include
operators may need to be broken down into multiple separate LINQ queries in order to avoid the cartesian explosion problem.
但我没有看到任何关于如何实际完成此操作的解释。
您应该考虑延迟加载此查询。
https://docs.microsoft.com/en-us/ef/core/querying/related-data
最终我手动编写了 SQL,我找不到使生成的 SQL 足够高效的方法。还要考虑优化数据库,例如添加聚簇索引。这大大减少了数据库时间。