Linq查询的数据库响应时间特别慢

时间:2009-01-16 22:35:49

标签: c# sql-server linq

我已经编写了我认为非常可靠的Linq语句,但执行时需要2到5秒的等待时间。有没有人想过如何加快这个速度?

            t.states = (from s in tmdb.tmZipCodes
                        where zips.Contains(s.ZipCode) && s.tmLicensing.Required.Equals(true)
                        group s by new Licensing { 
                            stateCode = s.tmLicensing.StateCode,
                            stateName = s.tmLicensing.StateName,
                            FIPSCode = s.tmLicensing.FIPSCode,
                            required = (bool)s.tmLicensing.Required,
                            requirements = s.tmLicensing.Requirements,
                            canWorkWhen = s.tmLicensing.CanWorkWhen,
                            appProccesingTime = (int) s.tmLicensing.AppProcessingTime 
                        }
                            into state
                            select state.Key).ToList();

我已将其更改为两阶段查询,该查询几乎是瞬间运行,通过执行一个独特的查询来使我的分组工作,但在我看来,运行速度比单个运行速度快一点反直觉查询。

3 个答案:

答案 0 :(得分:2)

我不确定为什么花了这么长时间,但查看LINQPad可能会有所帮助,它会显示正在生成的实际查询并帮助优化。

另外,它可能不是需要很长时间的实际查询,它可能是查询生成。我发现最长的部分是将linq转换为sql语句。

你可以使用编译的查询来加速sql生成过程。可以在3devs找到一些信息。我不是想宣传我的博客,但我认为它适合。

答案 1 :(得分:1)

我希望这无关紧要,但是

s.tmLicensing.Required.Equals(true)

看起来非常多(对我而言):

s.tmLicensing

假设它是布尔属性。

鉴于你知道这是真的,我认为在分组中也没有太多意义。

说完这些话之后,John Boker在两个方面都是绝对正确的:找出它是SQL还是LINQ,然后攻击相关位。

答案 2 :(得分:1)

您似乎没有使用该组,只需在最后选择密钥。那么,这是否与您想要的一样?

t.states = (from s in tmdb.tmZipCodes
            where zips.Contains(s.ZipCode) && s.tmLicensing.Required.Equals(true)
            select new Licensing { 
                stateCode = s.tmLicensing.StateCode,
                stateName = s.tmLicensing.StateName,
                FIPSCode = s.tmLicensing.FIPSCode,
                required = (bool)s.tmLicensing.Required,
                requirements = s.tmLicensing.Requirements,
                canWorkWhen = s.tmLicensing.CanWorkWhen,
                appProccesingTime = (int) s.tmLicensing.AppProcessingTime 
            }).Distinct().ToList();

还要记住,LINQ在必须执行之前不会执行查询。因此,如果您在两个语句中构建查询,则在调用ToList之前,它不会针对数据上下文(在本例中为SQL Server)执行该查询。当查询运行时,它会将多个查询合并为一个查询并执行该查询。