NOLOCK with Linq to SQL

后端 未结 5 636
小鲜肉
小鲜肉 2020-11-30 23:01

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

5条回答
  •  半阙折子戏
    2020-11-30 23:24

    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 ...

提交回复
热议问题