Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do linq generated queries get cached effectively by SQL Server 2008?

Do linq generated queries get cached effectively by SQL Server 2008?

or is it better to use stored procedures with linq or what about a view and then using compiled linq queries... opinions?

cheers

emphasis here is on "effectively", and or is it better....

ie. views are cached well by sql server, and then using linq on the view....

like image 258
alex Avatar asked Feb 06 '10 14:02

alex


3 Answers

On top of the answers already given according to Damien Guard there's a glitch in the LINQ to SQL and EF LINQ providers that fails to set the variable lengths consistently for queries involving string parameters.

http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache

Apparently it's fixed in .NET 4.0.

In the past I've written stored proc's in place of LINQ queries, mainly for complex reporting-like queries rather than simple CRUD but only following profiling of my application.

like image 54
John Foster Avatar answered Oct 06 '22 21:10

John Foster


L2S simply passes queries on to SQL Server 2008. So they will get cached, or not cached, like any other query submitted by any other process. The fact that a Linq query is compiled has no impact on how SQL Server processes the query.

like image 30
Randy Minder Avatar answered Oct 06 '22 19:10

Randy Minder


Queries that LINQ generates are normal SQL queries like your own hand-crafted SQL queries, and they follow the same rules: if the query text is identical (down to the last comma and whitespace) than a query text before, chances are its query execution plan might have been cached and thus able to be reused.

The point is: the query text has to be absolutely identical - if even a single whitespace is different, SQL Server considers it a new query and thus will go through the full process of parsing, analysing, finding a query plan and executing it.

But basically, yes - queries sent off by LINQ will be cached and reused - if they meet those criteria!

like image 41
marc_s Avatar answered Oct 06 '22 19:10

marc_s