tags:

views:

1161

answers:

1

Is it possible to get Linq2Sql to emit a NOLOCK in its SQL? And if so, how?

Kind regards Scott

+9  A: 

Yes it is, so here's the entry from my blog:

The NOLOCK hint is essentially the same as wrapping a query in a transaction whose "isolation level" is set to "read uncommitted". It means that the query doesn't care if stuff is in the process of being written to the rows it's reading from - it'll read that "dirty" data and return it as part of the result set.

Turns out that you can do the whole "read uncommitted" transaction thing using the old System.Transactions namespace introduced in .NET 2.0. Here's some sample code:

using (var txn = new TransactionScope(
    TransactionScopeOption.Required, 
    new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadUncommitted
    }
))
{
    // Your LINQ to SQL query goes here
}

So I'm creating a new TransactionScope object and telling it to use a read-uncommitted isolation level. The query within the "using" statement now acts as if all its tables were reading with the NOLOCK hint.

Here are the first results from a Google search for "linq sql nolock":

InfoQ: Implementing NOLOCK with LINQ to SQL and LINQ to Entities

Matt Hamilton - LINQ to SQL and NOLOCK Hints : Mad Props!

Scott Hanselman's Computer Zen - Getting LINQ to SQL and LINQ to ...

Matt Hamilton
If I wanted to be totally correct, none of these options actually "emit a NOLOCK" in the SQL itself - they use the transaction's isolation setting instead. Same thing, but not technically what the question asked.
Matt Hamilton
Copied the text from your blog, so that nobody has to click-through links to get to the answer.
Eric
No worries. My main point was that this stuff is easily discoverable on Google without having to ask here. This question will probably usurp the #1 place on Google for this search now. :)
Matt Hamilton
@Matt: That's the point! Create a canonical source! See: http://meta.stackoverflow.com/questions/8724/how-to-deal-with-google-questions/8729#8729
Eric
Yeah I dunno if I wholly agree with that idea. For me, Scott's or my blog post was the canonical source for that answer. I don't know if my stealing content from others' blogs (or even mine) is the right approach.
Matt Hamilton
Would have to aggree with Matt on the content stealing. Matt took the time to write the post on his blog. Now SOF is getting the traffic
Harry