【问题标题】:Can not load related data with Include or ThenInclude or Select/Many with ONE query [duplicate]无法使用 Include 和 ThenInclude 或 Select/Many 使用 ONE 查询加载相关数据 [重复]
【发布时间】:2016-12-13 20:25:05
【问题描述】:

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

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

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

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

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

但这会导致我只获得分配给测试的 TestTypes - innerjoin - 但我需要所有的 TestTypes 和他们的 Tests 和他们的 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; }


    }

【问题讨论】:

  • 按想法.Include(x =&gt; x.Tests.SelectMany(z =&gt; z.PupilsTests)) 应该是.Include(x =&gt; x.Tests).ThenInclude(x =&gt; x.PupilsTests)。这种情况下的结果是什么?您使用的是哪个 EF Core 版本?
  • 不.. .ThenInclude(x => x.NothinghereOnlyLinqMethods)。我使用 EF Core "Microsoft.EntityFrameworkCore": "1.0.1",
  • 可能是智能感知问题。尝试输入我在第一条评论中写的内容。
  • 该死...我记得一年前我遇到过智能感知问题。是的,你的提示奏效了!我现在在一个查询中获得我的数据!我忘记了这件事的根本原因是什么。我的意思是这个“错误”是旧的......你知道这个错误修复是否在 M$ 提交?谢谢,请根据您的建议创建解决方案!

标签: c# entity-framework-core


【解决方案1】:

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

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

注意!

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

【讨论】:

  • Intellisense 注意,很有帮助,考虑突出显示。
  • @AntonToshik 当然。现在它甚至被记录在案 - 请参阅 Including multiple levels 中的 Note
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多