如何在One Include之後執行多個ThenInclude導航道具

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();

這是官方方法還是有更好的方法?

UPDATE

   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事件探查器中看到查詢結果,則查詢是您假裝的,而不重複包含到TestType(僅與該表連接1)

你有另一種方法可以做到這一點,但我更喜歡以前的方式!

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow