I am using Entity Framework 6 in an MVC 5 project. As you're aware of, SELECT
queries in SQL Server perform faster and more efficient if we use WITH (NOLOCK)
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?
The NOLOCK and READUNCOMMITED hints should only be used with SELECT statements. If we try to use this for an UPDATE, DELETE or INSERT we will get an error. You will see this error. The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE, DELETE or MERGE statements.
Thus, we can say that Nolock reads “Dirty Data” when applied with only Select statement in SQL Server Database. While With (Nolock)do not issue any shared locks and exclusive locks. It is possible with With (Nolock) that, it can read an uncommitted transaction, which can be rolled back at the middle of a read.
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.
Write your own EntityFramework Provider.
Use a Command Interceptor to modify the statement before it is executed. http://msdn.microsoft.com/en-us/data/dn469464.aspx
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( TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted })) { using (var db = new MyDbContext()) { // query } }
EDIT: It's important to note also that NOLOCK for Updates and Deletes (selects remain intact) has been Deprecated by Microsoft as of SQL Server 2016 and and will be removed in 'a' future release.
https://docs.microsoft.com/en-us/sql/database-engine/deprecated-database-engine-features-in-sql-server-2016?view=sql-server-2017
You can use a workaround that don't use transaction scopes for each query. If you run the code below, ef will use the same transaction isolation level for the same Server Process ID. Since Server Process ID does not change in same request, only one call for each request is sufficient. This also works in EF Core.
this.Database.ExecuteSqlCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With