2009-01-16 64 views
1

我已经写了我认为是非常可靠的Linq语句,但是这会在执行时获得2到5秒的等待时间。有没有人想过如何加快速度?在Linq查询上特别慢的数据库响应时间

  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(); 

我把它改为其通过执行不同的查询,使我的工作编组运行几乎瞬间两个阶段的查询,但在我看来,这是一个有点直觉上有跑这么多比单个查询更快。

回答

2

林不知道为什么要花这么长,但它可能有助于看看LINQPad,它会告诉你正在生成的实际查询和帮助优化。

此外,它可能不是要带很长一段时间的实际查询,这可能是查询产生。我发现最长的部分是linq被转换为sql语句的时候。

你可能使用编译的查询,以加快SQL生成过程。有关信息可以在3devs找到。我不是想要宣传我的博客,但我认为它很合适。

1

我希望这是无关紧要的,但

s.tmLicensing.Required.Equals(true) 

看起来极(对我来说),如:

s.tmLicensing 

假设它是一个布尔值属性。

既然你知道这是真的,我没有看到无论是在分组拥有它远点。

说了那些东西,约翰·博克是在这两点完全正确的:找出是否是在SQL或LINQ,然后攻击的相关位。

+0

有时,当你复制并粘贴你的代码时,你忽略了一些细节。我有另一个功能,填充许可对象,我只是从中剥离了代码。 – thaBadDawg 2009-01-17 00:00:30

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)执行该查询。当查询运行时,它会将多个查询合并到一个查询中并执行该查询。