c# - 无法通过一个查询使用 Include 或 ThenInclude 或 Select/Many 加载相关数据

标签 c# entity-framework-core

<分区>

1 个测试分配了 1 个测试类型。

我需要加载与测试相关的所有 TestType 实体或不加载 Schoolclass 、 Subject 和 Assigned Pupils 到测试(PupilsTests)

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

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

当我使用 context.Tests

开始查询时,我只能获得带有测试的 PupilsTests

但这会导致我只得到分配给测试的测试类型 - 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<Test>();
    }
    // Props removed for clarity
    public int Id { get; set; }   
    public ISet<Test> 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<PupilTest>();
        }
        // Props removed for clarity
        public int Id { get; set; }           
        public ISet<PupilTest> PupilsTests { get; set; }
        public TestType TestType { get; set; }


    }

最佳答案

EF6 的 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 查询。

更新:现在 VS Intellisense 问题在 Including multiple levels 下的 EF Core 文档中特别提到。部分:

Note!

Current versions of Visual Studio offer incorrect code completion options and can cause correct expressions to be flagged with syntax errors when using the ThenInclude method after a collection navigation property. This is a symptom of an IntelliSense bug tracked at https://github.com/dotnet/roslyn/issues/8237. It is safe to ignore these spurious syntax errors as long as the code is correct and can be compiled successfully.

关于c# - 无法通过一个查询使用 Include 或 ThenInclude 或 Select/Many 加载相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41129970/

相关文章:

c# - 作为外键的字符串 - 无法将 lambda 表达式转换为类型 'string',因为它不是委托(delegate)类型

c# - DbSet 在 EF7 中没有 Find 方法

.net Core() 上的 Postgresql 存储过程

c# - 如何删除所有匹配和删除文本

c# - 如何指定打开excel文件的字符串路径?

c# - 如何监控网站的变化?

c# - 如何使用 LINQ 从 ZipArchive 中获取第一个匹配的文件?

c# - aspnet 核心 Entity Framework 7 自引用 "job"1 到多表

c# - EF Core HasData() 未在 OnModelCreating 内调用

c# - 复制 Excel 图表并将其移动到另一个工作表