在简单的Add()中被选为死锁受害者->保存更改() [英] Chosen as the deadlock victim on simple Add() -> SaveChanges()

查看:79
本文介绍了在简单的Add()中被选为死锁受害者->保存更改()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的程序

private static void Main(string[] args)
{
    Parallel.For(0, 1000000, InsertTestEntity);
}

private static void InsertTestEntity(int i)
{
    using (var dbContext = new TestDbContext())
    {
        dbContext.TestEntities.Add(new TestEntity { HugeString = "Baby shark," + string.Join(", ", Enumerable.Repeat("doo", 500)) });
        dbContext.SaveChanges();
    }
}

public class TestEntity
{
    [Key]
    public int Id { get; set; }

    public string HugeString { get; set; }
}

public class TestDbContext : DbContext
{
    public DbSet<TestEntity> TestEntities { get; set; }
}

抛出类似

System.Data.Entity.Infrastructure.DbUpdateException
  HResult=0x80131501
  Message=An error occurred while updating the entries. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at EntityFrameworkStressTest.Program.InsertTestEntity(Int32 i) in c:\Git\EntityFrameworkStressTest\EntityFrameworkStressTest\Program.cs:line 18
   at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()

Inner Exception 1:
UpdateException: An error occurred while updating the entries. See the inner exception for details.

Inner Exception 2:
SqlException: Transaction (Process ID 100) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

SQL表在SSMS中看起来像这样

The SQL table looks like this in SSMS

推荐答案

如SSMS屏幕截图所示,没有主键指示。在ID列旁边应该有一个钥匙符号。

As seen in the SSMS screenshot, there seem to be no indication of a primary key. There should have been a key symbol next to the ID column.

进一步检查发现,Id的确声明为身份(SQL Server for AUTO INCREMENT ),而不是主键。要使 Id 成为真正的主键,请在SSMS中的表上单击鼠标右键,然后选择设计,然后右键单击 Id 行。列设计器,然后单击设置主键:

Further inspection reveals that Id is indeed declared as identity (SQL Server for AUTO INCREMENT), but not as primary key. To make Id a real primary key right click the table in SSMS and choose Design, right click the Id row in the column designer and click SET PRIMARY KEY:

在此之后,压力测试将运行而不会死锁。

After this, the stress tests runs without deadlocking itself.

这篇关于在简单的Add()中被选为死锁受害者->保存更改()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆