使用它们的联结表获取根实体并包括它们的主表

Fetch root entity with their junction tables and include their principal tables

我有一个测试实体:

public class Test
{
    public Test()
    {
        PupilsTests = new HashSet<PupilTest>();
        TestTypeTests = new HashSet<TestTypeTest>();
        SchoolclassTests = new HashSet<SchoolclassTest>();
        SubjectTests = new HashSet<SubjectTest>();
    }

    public int Id { get; set; }
    public DateTime Date { get; set; }
    public int Number { get; set; }

    public ISet<PupilTest> PupilsTests { get; set; }
    public ISet<TestTypeTest> TestTypeTests { get; set; }
    public ISet<SchoolclassTest> SchoolclassTests { get; set; }
    public ISet<SubjectTest> SubjectTests { get; set; }

    public GradingKey ScoreGradeKey { get; set; }
    public Schoolyear Schoolyear { get; set; }
    public int SchoolyearId { get; set; }

}

我需要获取按 schoolyearId 过滤的所有测试实体,包括 连接表 SchoolclassTests、SubjectTests、TestTypeTests。

但是对于这些联结表,我还必须包括它们的 主表 Schoolclass、Subject、TestType

这是我试过的:

public async Task<IEnumerable<Test>> GetTestsAsync(int schoolyearId)
{
return await context.Tests.Where(t => t.SchoolyearId == schoolyearId)
                          .Include(t => t.SchoolclassTests)
                          .Include(t => t.SubjectTests)
                          .Include(t => t.TestTypeTests)
                          // How to include all 3 Principal tables? ThenInclude does not workk
                          // over all the 3...
                          .ToListAsync();
}

无论我尝试 .Include 或 ThenInclude 的任何组合,我都不会在一个查询中获得所有 3 个主表和联结表。

我该怎么做?

使用Select方法,您可以包含连接表的主表:

public async Task<IEnumerable<Test>> GetTestsAsync(int schoolyearId)
{
    return await context.Tests.Where(t => t.SchoolyearId == schoolyearId)
            .Include(t => t.SchoolclassTests.Select(s => s.Schoolclass))
            .Include(t => t.SubjectTests.Select(s => s.Subject))
            .Include(t => t.TestTypeTests.Select(t => t.TestType))                
            .ToListAsync();
}