简体   繁体   English

Linq查询非常慢

[英]Linq queries are very slow

I have a table that contains a list of builds. 我有一个包含构建列表的表。 What I am trying to achieve is to group those builds by reference ID and take 5 or 10 latest (by build_date ) and see check their statuses. 我想要实现的是按参考ID对这些构建进行分组,并采用5或10的最新版本(按build_date ),然后查看其状态。 So I am currently doing the group by and returning them. 因此,我目前正在做小组并返回他们。

using (var ctx = new Entities())
{
    return ctx.Builds.Where(x => x.build_date > dateTime)
                .GroupBy(x => new
                {
                    x.configuration_id
                })
                .Select(s => new ConfigurationBuilds
                {
                    ConfId = s.Key.configuration_id,
                    Builds = s.Select(x => x).OrderByDescending(d => d.build_date).Take(count)
                })
                .ToList();
}

Later on in another method I will check all the statuses Builds items to see if they match any criteria, something like: 稍后,在另一种方法中,我将检查Builds项目的所有状态,以查看它们是否符合任何条件,例如:

items.Where(build => build.Builds.Count() >= 9)
                    .Where(build => build.Builds.All(x => !x.build_status.Equals("SUCCESSFUL")))
                    .ToList();

The problem is with the first query where I do groupBy . 问题出在我执行groupBy的第一个查询中。 That one is extremelly slow, how could I optimize that routine? 那太慢了,我该如何优化这个程序呢?

I createad a dummy routine to select all builds and group by statuses 我创建了一个虚拟例程来选择所有构建并按状态分组

var items = ctx.Builds.Where(x => x.build_date > dateTime).OrderByDescending(x=>x.build_id)
                    .GroupBy(x => new {
                        confID = x.configuration_id,
                        status = x.build_status
                        })
                .Select(s => new 
                    {
                        Id = s.Key.confID,
                        Status = s.Key.status,
                        Cnt = s.Count()
                    }).OrderBy(d=>d.Id)
                    .ToList();

This one on same data is blazing fast, but does not really do what I need. 这个在相同数据上的速度很快,但是并不能真正满足我的需求。 I need to: For each configuration group select n number of latest builds that match some criteria. 我需要:对于每个配置组,请选择n个符合某些条件的最新版本。 How to do that? 怎么做?

A good way way is to determine what SQL it's generating is to use a tool like LINQpad . 确定生成的SQL的好方法是使用LINQpad之类的工具。 Once you get an idea of what the SQL looks like, you can use SQL tools like execution plan generation. 一旦了解了SQL的外观,就可以使用SQL工具,例如执行计划生成。

Or you can use SQL profiler to see what's going on with the SQL queries too. 或者,您也可以使用SQL事件探查器来查看SQL查询的最新情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM