如何编写这个linq查询,使它不那么慢

bwleehnv  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(99)

我有一个SQL语句,运行它时非常快速:

select Distinct statuses.Description, count(*) as count 
from referrals 
inner join statuses on referrals.StatusId = statuses.id
group by statuses.Description

但是当我用Entity Framework Core运行下面的linq代码时,运行几乎需要5分钟,数据库中只有680行。

var data = context.Referrals
                  .Include(s => s.Status).AsEnumerable()
                  .GroupBy(r => r.Status)
                  .Select(g => new StatusCountItem 
                                   { 
                                       Status = g.Key.Description, 
                                       Count = g.Select(r => r).Count() 
                                   }).ToList();

有没有一种方法可以编写一个类似的Linq语句,而不会一直运行下去,或者我需要找到一种不同的方法来完成我想要的任务?

    • EDIT**:当我没有AsEnumerable时,我收到此错误消息,这就是我添加它的原因:

LINQ表达式'DbSet(). Join(inner:数据集()、
外部键选择器:如果您的数据库中包含了一个新的数据库,那么您就可以使用这个新的数据库了。
内部键选择器:如果您有一个新的属性,那么您就可以使用它。
结果选择器:(o,i)=〉新透明标识符〈引用,状态〉(外部= o,内部= i))
. GroupBy(r =〉r. Inner)"无法转换。请以可以转换的形式重写查询,或者通过插入对" AsEnumerable "、" AsAsyncEnumerable "、" ToList "或" ToListAsync "的调用来显式切换到客户端计算

nx7onnlm

nx7onnlm1#

试试这个:

var data = context.Referrals
    .GroupBy(r => r.StatusId) // notice the change here, you need to group by the id
    .Select(g => new StatusCountItem()
    {
        Status = g.First().Status.Description,
        Count = g.Count()
    }).ToList();
alen0pnh

alen0pnh2#

您的SQL查询是根据context.Referrals.Include(s => s.Status).AsEnumerable()建立的,相当于:

select *
from referrals 
    inner join statuses on referrals.StatusId = statuses.id

注意星星,您正在查询 every 列,换句话说,删除查询中间的随机AsEnumerable()

8xiog9wr

8xiog9wr3#

使用这个方法,它很简单,而且可以提高查询性能。

from r in context.Referrals
join s in context.statuses on r.StatusId equals s.Id
select new { s.Description, r.StatusId , S.Id) into result
group result by new { s.Description } into g
select new {
   CompanyName = g.Key.Description,
   Count = g.Count()
}

相关问题