Get Entity Framework 6 use NOLOCK in its underneath SELECT statements

后端 未结 4 677
星月不相逢
星月不相逢 2020-12-24 01:28

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 (NOL

4条回答
  •  借酒劲吻你
    2020-12-24 01:44

    I agree with what codeworx says in a way that Read Uncommitted can be dangerous. If you can live with dirty reads, go for it.

    I found a way to make this work without changing anything in the current queries.

    You need to create a DbCommandInterceptor like this:

    public class IsolationLevelInterceptor : DbCommandInterceptor
    {
        private IsolationLevel _isolationLevel;
    
        public IsolationLevelInterceptor(IsolationLevel level)
        {
            _isolationLevel = level;
        }
    
    
    
        //[ThreadStatic]
        //private DbCommand _command;
    
    
        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            SetTransaction(command);
    
        }
    
        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            SetTransaction(command);
        }
    
        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            SetTransaction(command);
        }
    
    
    
    
        private void SetTransaction(DbCommand command)
        {
            if (command != null)
            {
                if (command.Transaction == null)
                {
                    var t = command.Connection.BeginTransaction(_isolationLevel);
                    command.Transaction = t;
                    //_command = command;
                }
            }
        }
    
    }
    
    
    

    then at the cctor (static contructor of your dbcontext) just add the interceptor to the DbInfrastructure of entity framework collections.

    DbInterception.Add(new IsolationLevelInterceptor());
    

    this will for each command that EF sends to the store, wraps over a transaction with that Isolation Level.

    In my case worked well, since we write data through an API where that data is not based on the readings from the database. (data can be corrupted because of the dirty reads) and so worked fine.

    提交回复
    热议问题