c# - 如何更快地对子实体进行分组和计数?
问题描述
我的查询很慢...
我写了以下查询,这个查询给了我预期的结果。
dbContext.ParentEntity.GroupBy(x => new { x.Propery1, x.Propery2}, (key, group) => new
{
Propery_1= key.Propery1,
Propery_2= key.Propery2,
Count = group.Sum(x => x.Level1Childs.SelectMany(x => x.Level2Childs.SelectMany(x => x.Level3Childs).Where(x => x.IssuposedToBeCounted()).Count())
}).ToList()
它向 DB 发出 x.Propery1.count * x.Propery2.count 请求...如何重写查询以使其更快?
解决方案
这称为N+1 问题。尝试从数据库中获取所有数据一次,然后做任何你想做的事情。例如在 ORM 工具中,这通常来自延迟加载。
推荐阅读
- python - How can I append values from a JSON dictionary to a new list?
- oracle - Rolling back Oracle Transction if not committed within certain minutes
- css - 在 Bulma 导航栏中调整品牌徽标的大小(Angular 7)
- android - 无法获取资源'http://...firebase-measurement-connector-impl-17.0.5-javadoc.jar
- python - Python(硒)中的网络搜索自动化没有返回结果
- javascript - Javascript:从 HTML 输入返回值的问题
- python - 如何在 Python 中使用多个但数量有限的线程来处理列表
- sql - 高效地将一对多多对多数据库映射到 Golang 中的结构
- matlab - 如何从一组符号方程中生成一个作为特定变量函数的方程?
- python - 通过嵌入字典的列表进行过滤