如何在One Include之后执行多个ThenInclude导航道具

时间:2016-12-03 23:26:27

标签: entity-framework-core

对于TestType,我想包括导航道具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; }
    }

3 个答案:

答案 0 :(得分:3)

最好的方法是你之前写的,有两个.Include(t =&gt; 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事件探查器中看到查询结果,则查询是您假装的,而不重复包含到TestType(仅与该表连接1次)

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

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

答案 1 :(得分:0)

如果这种类型的包含在您的代码库中很常见,那么创建几个扩展方法可能是有用的:

test 1 false + test 2 false: case 1 -- no user interaction available
test 1  true + test 2 false: case 2 -- interact via XWindows
test 1 false + test 2  true: case 3 -- interact via STDIN/console
test 1  true + test 2  true: case 4 -- XWindows or STDIN/console, whichever is preferred

通过此操作,您可以将查询更改为

"sort": {
  "_script" : {
    "script" : {
     "source" : "params._source.participants[0].participantEmail.toLowerCase()",
     "lang" : "painless"
   },
   "type" : "string",
   "order" : "desc"
 }

尽管这不支持深度超过2个级别。

答案 2 :(得分:-1)

为什么不两次使用Include

  var myVar= ((MyContext) _context)
            .MasterEntity
            .Include(x => x.FirstChild)
            .Include(x=>x.FirstChild.FirstGrandChild)
            .Include(x=>x.FirstChild.SecondGrandChild)
            .Where(x => x.Id== input)
            .ToList();