1

我们的 C# / LINQ to EF 代码中有一个查询,它在通过我们的 Web 应用程序 (ASP.NET MVC) 运行时始终导致超时。

错误信息:

执行超时已过期。
在操作完成之前超时时间已过或服务器没有响应。

直接在 SSMS 中运行由 LINQ 生成的 SQL 几乎是瞬时的,无论返回或查询的数据大小如何(我们在查询中使用日期范围)。

这个答案解决了超时问题:我们跑了

exec sp_updatestats 

在数据库上,现在超时不再发生

但是,正如评论中提到的,这是否解决了实际问题?

它是否可以防止问题在将来发生?

  1. 由于查询没有导致直接在 SSMS 中运行的任何问题,这是否表明 ASP.NET / EF 存在问题?

  2. 还是维护计划是正确的方法?我对维护计划一无所知。我看到有关重建索引、备份等的问题。如果我需要维护计划来防止将来发生此超时问题,我必须设置哪种类型的计划?

4

1 回答 1

3

I'll first mention that regular database maintenance that includes updating stats and/or index reorgs is a best practice. This can be implemented with a maintenance plan, the popular Ola Hallengren's SQL Server Maintenance Solution, or your own scripts. Ola's solution selectively performs maintenance based on thresholds to avoid unneeded overhead.SQL Server uses a cost-based optimizer so more accurate row count estimates gleaned from statistics will help provide most optimal execution plans.

The significantly different query performance between SSMS and the app code suggests different execution plans. As to why the plans might be different for the same query, I suggest you peruse Erland Sommarskog's article Slow in the Application, Fast in SSMS for details. Common causes for different plans include different session SET options or parameter sniffing as detailed in the article. Also, note you'll need to execute the SSMS query using a parameterized sp_executesql query to better mimic the parameterized query EF executes. Local variables or literals in SSMS are not the same thing as parameters and may result in different plans.

When you run sp_updatestats, not only does it update statistics, it will invalidate cached execution plans so it addresses both parameter sniffing and stale stats. DBCC FREEPROCCACHE alone would address parameter sniffing, which should be targeted to the problem plan alone in a production OLTP environment.

于 2017-11-19T12:21:47.797 回答