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.
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.
using (new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadUncommitted
}))
{
using (var db = new MyDbContext()) {
// query
}
}
Ref : https://stackoverflow.com/questions/24684914/get-entity-framework-6-use-nolock-in-its-underneath-select-statements
public static IList ToListNolock(this IQueryable query)
ReplyDelete{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted }))
{
IList toReturn = query.ToList();
scope.Complete();
return toReturn;
}
}
private static TransactionScope _TransactionScope { get { return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted }); } }
ReplyDeletepublic static List ToListNolock(this IEnumerable query)
{
using (_TransactionScope) { return Enumerable.ToList(query); }
}
public static T FirstOrDefaultNolock(this IEnumerable query)
{
using (_TransactionScope) { return Enumerable.FirstOrDefault(query); }
}