下面有一个查询,它获取所有这些子实体(例如。( PracticedStyles、ReceivedReviews、InstructedPoses等)
我所需要的只是这些子集合的.count()。
问题--是否有更快的方法来运行这个查询来获取这些包含的计数,然后使用下面的查询?运行时间为4-7秒,而DB中的数据非常少。
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);发布于 2021-11-04 03:56:18
当然有。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);这将创建一个匿名类,其中包含用户以及所需的所有计数。
https://stackoverflow.com/questions/69834275
复制相似问题