我在EF Core 2.0中有这样的linq查询,它按原样工作,但是当我升级到EF Core 3.0时,它总是超时。我在query = query.Where(x => x.Questions);
中发现了问题。
我的问题是我想返回仅带Take(10)或带过滤条件的课程。条件仅显示特定范围而不是所有问题。
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();
答案 0 :(得分:3)
EFCore 3.0更改了使用.Include()
生成的查询,您遇到了笛卡尔爆炸问题;
具体来说,现在文档中有以下红色警告:
注意
从3.0.0版开始,每个Include都会导致一个附加的JOIN 添加到关系提供程序产生的SQL查询中,而 早期版本生成了其他SQL查询。这个可以 显着改变查询的性能,以达到更好或 更差。特别是,LINQ查询中的查询数量极高 包含运算符可能需要细分为多个单独的 LINQ查询是为了避免笛卡尔爆炸问题。
解决方案是现在根据文档执行多个查询。
它的超级不幸的加载实体图(对高度规范化的数据通用)非常糟糕,但这是EF的当前状态。
请参阅:加载Related Data并滚动直到看到红色。
答案 1 :(得分:0)
var query = _courseRepository.Table
.Include(x => x.Questions)
.Include(x => x.CourseClasses)
.Include(x => x.CourseYear)
.Include(x => x.CourseSubject);
var course = await query.FirstOrDefaultAsync(x => x.Id == id);
query.Include(x => x.Instructors).ThenInclude(y => y.User).SelectMany(a => a.Instructors).Load();
query.Include(x => x.Instructors).ThenInclude(y => y.Course).SelectMany(a => a.Instructors).Load();
query.Include(x => x.Instructors).ThenInclude(y => y.CourseClass).SelectMany(a => a.Instructors).Load();
query.Include(x => x.CourseSections).ThenInclude(y => y.Lessons).SelectMany(a => a.CourseSections).Load();
query.Include(x => x.UserCourses).ThenInclude(y => y.User).SelectMany(a => a.UserCourses).Load();