使用Include或ThenInclude或Select / Many with ONE查询无法加载相关数据

1测试分配了1个TestType。

我需要加载与Test OR not和Schoolclass,Subject和Assigned Pupils相关的所有TestType实体到测试(PupilsTests)

.SelectMany或.Select在运行时失败。

我尝试了Include和ThenInclude的不同组合,但没有机会通过PupilsTests进行测试。

当我使用context.Tests开始查询时,我只能通过测试获得PupilsTests

但结果是我只得到TestTypes分配给Test – innerjoin – 但我需要所有TestTypes及其测试和他们的PupilsTests,我想在一个查询中。

 var testtypes = await context.TestTypes .Include(x => x.Schoolclass) .Include(x => x.Subject) .Include(x => x.Tests.SelectMany(z => z.PupilsTests)) .Where(t => t.SchoolyearId == schoolyearId) .AsNotTracking() .ToListAsync(); public class TestType { public TestType() { Tests = new HashSet(); } // Props removed for clarity public int Id { get; set; } public ISet Tests { get; set; } public Schoolyear Schoolyear { get; set; } public Schoolclass Schoolclass { get; set; } public Subject Subject { get; set; } public int SchoolyearId { get; set; } } public class Test { public Test() { PupilsTests = new HashSet(); } // Props removed for clarity public int Id { get; set; } public ISet PupilsTests { get; set; } public TestType TestType { get; set; } } 

EF Core的EF Core等效语法

 .Include(x => x.Tests.SelectMany(z => z.PupilsTests)) 

 .Include(x => x.Tests).ThenInclude(x => x.PupilsTests) 

请注意, ThenInclude似乎存在VS Intellisense问题,因此只需键入上面的内容即可成功编译并运行。

另请注意,EF Core进程集合包含不同(不使用EF6中的单个查询),因此上面将生成并执行3个SQL查询。

更新:现在,在包含多个级别部分的EF Core文档中特别提到了VS Intellisense问题:

注意!

当前版本的Visual Studio提供了错误的代码完成选项,并且在收集导航属性之后使用ThenInclude方法时,可能会导致正确的表达式被标记为语法错误。 这是在https://github.com/dotnet/roslyn/issues/8237上跟踪的IntelliSense错误的症状。 只要代码正确并且可以成功编译,就可以安全地忽略这些伪造的语法错误。