Get Entity Framework 6 use NOLOCK in its underneath SELECT statements

后端 未结 4 684
星月不相逢
星月不相逢 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:58

    In our project we use combination of the second and third solutions, suggested by @Cem Mutlu and @anotherNeo.

    Experiment with Sql Profiler showed that we have to use pair of commands:

    • READ UNCOMMITTED
    • READ COMMITTED

    because NET reuse connections via SqlConnectionPool

    internal class NoLockInterceptor : DbCommandInterceptor
    {
        public static readonly string SET_READ_UNCOMMITED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
        public static readonly string SET_READ_COMMITED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED";
    
        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            if (!interceptionContext.DbContexts.OfType().Any())
            {
                return;
            }
    
            ExecutingBase(command);
        }
    
        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            if (!interceptionContext.DbContexts.OfType().Any())
            {
                return;
            }
    
            ExecutingBase(command);
        }
    
        private static void ExecutingBase(DbCommand command)
        {
            var text = command.CommandText;
            command.CommandText = $"{SET_READ_UNCOMMITED} {Environment.NewLine} {text} {Environment.NewLine} {SET_READ_COMMITED}";
        }
    }
    
        

    提交回复
    热议问题