NOLOCK with Linq to SQL

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 …

Leave a Comment