Arash Arash - 1 year ago 424
C# Question

Get Entity Framework 6 use NOLOCK in its underneath SELECT statements

I am using Entity Framework 6 in an MVC 5 project. As you're aware of,

queries in SQL Server perform faster and more efficient if we use
in them. I checked out a few SQL SELECT statements generated by Entity Framework 6 and realized that none of them contain NOLOCK. I do not want to use transactions in my fetch operations to read from uncommitted transactions.
How can I enforce EF 6 to use NOLOCK in the underneath generated SELECT statements
? Your feedback is greatly appreciated. Thanks.

Answer Source

First of all... You should NEVER EVER use NOLOCK for each and every SQL Statement. It could compromise the integrity of your data.

It’s like any other query hint a mechanism you should only use when you do something out of the ordinary.

There is no way to tell the EF Provider to render the NoLock hint. If you really need to read uncommitted data you have the following option.

  1. Write your own EntityFramework Provider.

  2. Use a Command Interceptor to modify the statement before it is executed.

  3. Use a TransactionScope with IsolationLevel.ReadUncommited.

I know you said you do not want to use Transactions but it's the only out-of-the box way to read uncommitted data. Also it does not produce much overhead as each statement in SQL Server “implicitly” runs in a transaction.

using (new TransactionScope(
                    new TransactionOptions 
                         IsolationLevel = IsolationLevel.ReadUncommitted 
        using (var db = new MyDbContext()) { 
            // query