首页 > 解决方案 > 如何更快地对子实体进行分组和计数?

问题描述

我的查询很慢...

我写了以下查询,这个查询给了我预期的结果。

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 请求...如何重写查询以使其更快?

标签: c#entity-frameworklinq

解决方案


这称为N+1 问题。尝试从数据库中获取所有数据一次,然后做任何你想做的事情。例如在 ORM 工具中,这通常来自延迟加载


推荐阅读