首页 > 解决方案 > EF Core 3.0 .Include 不能按预期工作并且超级慢

问题描述

我在 EF Core 2.0 中有这样的 linq 查询,它按原样工作,但是当我升级到 EF Core 3.0 时它总是超时。我在query = query.Where(x => x.Questions);.
我的问题是我想返回带有过滤问题的课程,例如仅 Take(10) 或仅显示特定范围而不是所有问题的 .Where 条件。

var query = _courseRepository.Table;
query = query.Where(x => x.Id == id);
query = query.Include(x => x.Questions);
query = query.Include(x => x.CourseYear);
query = query.Include(x => x.CourseSubject);
query = query.Include(x => x.Instructors).ThenInclude(y => y.User);
query = query.Include(x => x.Instructors).ThenInclude(y => y.Course);
query = query.Include(x => x.Instructors).ThenInclude(y => y.CourseClass);
query = query.Include(x => x.CourseSections);
query = query.Include(x => x.CourseSections).ThenInclude(y => y.Lessons);
query = query.Include(x => x.CourseClasses);
query = query.Include(x => x.UserCourses).ThenInclude(y => y.User);
var result = query.FirstOrDefault();

标签: c#ef-core-2.2ef-core-3.0

解决方案


EFCore 3.0 更改了使用生成的查询.Include(),您遇到了笛卡尔爆炸问题

具体来说,现在文档中有以下红色警告:

警告

从 3.0.0 版本开始,每个 Include 都会导致将额外的 JOIN 添加到由关系提供程序生成的 SQL 查询中,而以前的版本会生成额外的 SQL 查询。这可以显着改变查询的性能,无论好坏。特别是,包含大量运算符的 LINQ 查询可能需要分解为多个单独的 LINQ 查询,以避免笛卡尔爆炸问题。

解决方案是现在根据文档执行多个查询。

它非常不幸的加载实体图,对于高度规范化的数据很常见,性能不佳,但这是它在 EF 中的当前状态。

请参阅:加载相关数据并滚动直到看到红色。


推荐阅读