c# - 如何在一个 Include 之后执行多个 ThenIninclude 导航 Prop

标签 c# entity-framework-core

对于 TestType,我想包含导航 Prop Schoolclass 和 subject。

我可以做:

.Include(t => t.TestType)
 .ThenInclude(x => x.Subject)

但不是:

.Include(t => t.TestType)
.ThenInclude(x => x.Subject)
.ThenInclude(x => x.Schoolclass)

因此我尝试了一个小技巧并且成功了:

我包含了 TestType 2 次...

var test = await context.Tests.Where(t => t.SchoolyearId == schoolyearId)
                                          .Include(t => t.TestType)
                                          .ThenInclude(x => x.Subject)
                                           .Include(t => t.TestType)
                                          .ThenInclude(x => x.Schoolclass)
                                           .AsNoTracking()
                                          .ToListAsync();

这是官方方法还是有更好的方法?

更新

   public class TestType
    {
        public TestType()
        {
            Tests = new HashSet<Test>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int Weight { 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; }
    }

最佳答案

最好的方法是你之前写,用两个.Include(t => t.TestType)

var test = await context.Tests.Where(t => t.SchoolyearId == schoolyearId)
                                      .Include(t => t.TestType)
                                      .ThenInclude(x => x.Subject)
                                       .Include(t => t.TestType)
                                      .ThenInclude(x => x.Schoolclass)
                                       .AsNoTracking()
                                      .ToListAsync();

如果您在 SQL Profiler 中看到查询结果,则该查询是您假装的,没有重复包含到 TestType(仅与该表有 1 个联接)

你还有另一种方法可以做到这一点,但我更喜欢以前的方法!

.Include("TestType.Subject") 
.Include("TestType.Schoolclass")  

关于c# - 如何在一个 Include 之后执行多个 ThenIninclude 导航 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953665/

相关文章:

c# - ChangeTracker.Entries() CurrentValue 等于 EF7 中的 OriginalValue

c# - 需要空数据库的 Entity Framework 代码优先单元测试

entity-framework - EF Core 2.0/2.1 - 如何有效地处理不常访问的大型列?

c# - 使用 Fluent API EF Code First 出现约束问题

c# - Microsoft JScript 运行时错误 : 'null' is null or not an object

c# - EF Core 通过空检查破坏了构造函数的目的

c# - 使用 EF Core 2.1 检查表是否存在

c# - 避免在 switch 语句中进行硬编码

c# - C# 方法链可以是 "too long"吗?

c# - 如何在 C# 中将一种日期格式更改为另一种日期格式,例如 10/10/2014 更改为 2014-10-10(年-月-日)?