[英]Very slow query in EF Core that fetches multiple children entities with .Include()?
我在下面有這個查詢,它獲取所有這些子實體(例如,PracticedStyles、ReceivedReviews、InstructedPoses 等)
我只需要這些子集合的 .count() 。
問題- 是否有更快的方法來運行此查詢以獲取這些包含的計數,然后在下面使用此查詢? 運行時間約為 4-7 秒,而且數據庫中的數據很少。
var userWithChildren = await _dbContext.Users
.Include(p => p.Yogabands.Where(p => p.IsActive == true))
.Include(p => p.PracticedStyles)
.Include(p => p.PracticedPoses)
.Include(p => p.ReceivedReviews)
.Include(p => p.InstructedStyles)
.Include(p => p.InstructedPoses)
.Include(p => p.InstructorPrograms)
.FirstOrDefaultAsync(user => user.UserName == userName);
絕對有。 Include
是一個簡單的工具,它返回連接上的每一行。 更糟糕的是,由於 SQL 的操作方式,您可以以規范化的形式返回結果,這意味着返回的總行數是所有這些計數相乘后的結果。 使用盡可能多的包含,這可能是數萬行。
你想要的是一個投影,像這樣:
var userWithChildren = await _dbContext.Users
.Select(p => new
{
user = p,
YogaBandCount = p.Yogabands.Where(yb => yb.IsActive == true).Count(),
PracticedStylesCount = p.PracticedStyles.Count(),
PracticedPosesCount = p.PracticedPoses.Count()
ReceivedReviewsCount = p.ReceivedReviews.Count(),
InstructedStylesCount = p.InstructedStyles.Count(),
InstructedPosesCount = p.InstructedPoses.Count()
InstructorProgramsCount = p.InstructorPrograms.Count()
})
.FirstOrDefaultAsync(p => p.user.UserName == userName);
這將創建一個匿名類,其中包含用戶以及您需要的所有計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.