数据库中的锁

  • EF操作数据库有时会出现如下异常
    • 从存储区提供程序的数据读取器中进行读取时出错...........事务(进程 ID *)与另一个进程被死锁在 锁 资源上,并且已被选作死锁牺牲品。请重新运行该事务。
    • 原因:通过EF操作数据库时发生了死锁,这有可能是因为数据库同时有数据库同步、OGG等事务进程在进行。
    • 解决方法:
      • 貌似只能缓解
      • 如果业务上允许部分数据的脏读(不及时)
        • EF读数据时允许读取脏数据
          •  1 public static List<T> ToListReadUncommitted<T>(this IQueryable<T> query)
             2         {
             3             using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
             4             {
             5                 List<T> toReturn = query.ToList();
             6                 scope.Complete();
             7                 return toReturn;
             8             }
             9         }
            10 
            11         public static int CountReadUncommitted<T>(this IQueryable<T> query)
            12         {
            13             using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
            14             {
            15                 int toReturn = query.Count();
            16                 scope.Complete();
            17                 return toReturn;
            18             }
            19         }
            View Code
        • sql查询增加nolock
        • 处理一个数据库死锁的异常时候,其中一个建议就是使用 NOLOCK 或者 READPAST,NOLOCK 和 READPAST 都是处理查询、插入、删除等操作时候,如何应对锁住的数据记录。NOLOCK 可能把没有提交事务的数据也显示出来.READPAST 会把被锁住的行不显示出来。不使用NOLOCK 和 READPAST ,在 Select 操作时候则有可能报错误:事务(进程 ID **)与另一个进程被死锁在 锁 资源上,并且已被选作死锁牺牲品。

原文地址:https://www.cnblogs.com/wyp1988/p/9927926.html