2017-06-26 87 views
0

执行查询我有以下的Linq:死锁SQLServer中

   var qry = s.GetTable<MessageEventDTO>().Where(x => x.MessageName == messageName && x.SourceTyp == sourceTyp && x.Source == source && (x.Status == MessageEventStatus.open || x.Status == MessageEventStatus.acknowledged)); 

       goneMessages = qry.ToList(); 

       var ret = qry 
        .Set(x => x.Status, x => x.Status | MessageEventStatus.gone) 
        .Set(x => x.TimestampGone, timeStamp) 
        .Update(); 
       return ret; 

至极将被转换为SQL语句:

 UPDATE MessageEvents SET Status = Status | 1, TimeStampGone = @1 WHERE MessageName = @2 AND SourceTyp = @3 Source = @4 AND (Status = 0 OR Status = 2) 

问题是现在有多个更新并行运行,我有死锁例外,但我不明白为什么?

enter image description hereenter image description here

+0

你有在桌子上什么指标?索引调整通常会避免死锁。 –

+0

您是否在代码中打开交易?我认为这不应该发生在你不使用交易时...... –

回答

0

看到,如果你不希望其他进程能够启动更新的选择部分,用UPDLOCK提示或设置适当的事务隔离级别(REPEATABLE READ)。

请参阅John Huang's Blog以更全面地了解非聚集索引如何导致死锁。

使用LINQ to SQL这是不是猎物这个问题举例:

var opts = new TransactionOptions(); 
opts.IsolationLevel = IsolationLevel.RepeatableRead; 
using (var txn = new TransactionScope(TransactionScopeOption.Required, opts)) 
{ 
    // update command goes here. 

    txn.Complete(); 
}