EntityFramework优化:查询WITH(NOLOCK)

1.SQL Server查询中WITH(NOLOCK)

  SELECT语句中加上WITH(NOLOCK)为解决阻塞死锁。

  处理数据库死锁异常查询的一种方式是使用NOLOCK 或 READPAST。

    ◊ NOLOCK:可能显示没有提交事务的数据

    ◊ READPAST:不显示被事务锁住数据

1.1 没有提交的事务,NOLOCK 和 READPAST处理的策略

CREATE TABLE [dbo].[Role](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RoleName] [nvarchar](100) NOT NULL,
    CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    ))
BEGIN TRANSACTION 
INSERT INTO [dbo].[Role](RoleName) VALUES ('教师')

1.2 对被锁住的记录,NOLOCK 和 READPAST处理的策略

INSERT INTO [dbo].[Role](RoleName) VALUES ('教师'),('学生')
BEGIN TRANSACTION
UPDATE [dbo].[Role] SET [RoleName] = 'Teacher' WHERE ID = 1

2. EntityFramework查询WITH(NOLOCK)

using System;
using System.Transactions;

namespace Libing.App
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new LibingContext())
            {
                using (var ts = new TransactionScope(TransactionScopeOption.Required,
                    new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
                {
                    var role = context.Set<Role>().Find(1);
                }
            }
        }
    }
}

  使用TransactionScope来避免查询对于它所读取的表的锁定。

posted @ 2018-05-17 20:56  libingql  阅读(561)  评论(0编辑  收藏  举报