LINQ to SQL Gotchas - Using Stored procedures - SimonS Blog on SQL Server Stuff

LINQ to SQL Gotchas - Using Stored procedures

I'm currently on the "I like LINQ to SQL" side of the fence. I think it is very much a marmite question, you love it our you hate it. But importantly you often hate it even if you haven't tried it.

I've been digging around with LINQ recently and whilst it is very nice and easy to do things. This, as with many situations, can cause problems if you don't know what is being done under the hood.

Mike Taulty is font of knowledge when it comes to LINQ and Entity Framework and he recently posted about the use of stored procedures in LINQ. (LINQ to SQL, Stored Procs, Output Params, Readers Reading)

One thing you find out is that LINQ may not execute a query on the line of code you think it will, i.e.

var query = ctx.GetCustomersByCountry("UK");

Will not execute the procedure associated with the GetCustomersByCountry method. It will only get executed when you do something with query.

Whats more when the procedure returns a resultset and you then iterate over that resultset the results are read from the server one at a time. This means that if you do complex processing in your loop you can tie up resources and a connection to your database.

For more details look at Mike's blog post (LINQ to SQL, Stored Procs, Output Params, Readers Reading)

Whilst this isn't as bad as serverside cursors in the old ADO days it is still a gotcha you have to be careful of.



-
Published 25 March 2008 17:09 by simonsabin
Filed under: ,

Comments

25 March 2008 20:06 by TheSQLGuru

# re: LINQ to SQL Gotchas - Using Stored procedures

Why is it you don't think this is as bad as the server-side cursors from the ADO days?  Seems pretty much identical to me.  

Also bad is that you may have transactioning in place, expecting to have actually acquired the var query value in your example when in actuality you haven't.

25 March 2008 21:46 by simonsabin

# re: LINQ to SQL Gotchas - Using Stored procedures

It my be my misunderstanding of how a data reader works.

The big issue with client side cursors was the overhead in network round trip in calling sp_cursorfetch (or something similiar) and most hadn't change the default fetch size so it did one per row.

That meant that perf sucked full stop. However with a data reader I believe the behaviour is different.

# Dew Drop - March 26, 2008 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop - March 26, 2008 | Alvin Ashcraft's Morning Dew

12 December 2008 21:59 by SQL Server 2008 (SSQA.net)

# LINQ to SQL - will this be a future of database development?

Since the CTP of SQL Server 2008 there has been much of traffic going around talking LINQ is a replacement