并行插入多行时实体框架出现死锁

Pab*_*lla 5 entity-framework-4 database-deadlocks

我们在使用 EF 并行插入多个实体时遇到问题。WCF 操作由许多进程调用,以在每次调用中生成具有不同分布式事务的实体。正如我们在 sql server profiler 中看到的,它生成以下 sql:

(@0 int,@1 nvarchar(32),@2 datetime2(7),@3 nvarchar(64),@4 int,@5 int,@6 bit)
insert [dbo].[CommandRequests](
   [CommandId]
 , [DeviceId]
 , [StartDateTime]
 , [EndDateTime]
 , [Parameters]
 , [Caller]
 , [Result]
 , [Priority]
 , [Timeout]
 , [ParentRequestId]
 , [IsSuccessful]
 , [Host])
  values (@0, @1, @2, null, null, @3, null, @4, @5, null, @6, null)

  select [CommandRequestId]
  from [dbo].[CommandRequests]
  where @@ROWCOUNT > 0 and [CommandRequestId] = scope_identity()   
Run Code Online (Sandbox Code Playgroud)

所以 EF 给我们一个插入,然后是一个选择。因为它是并行完成的,所以很多都因死锁而中止。

我们使用的是 EF 4.0,而不是 4.1 或 4.2。

知道如何解决这个问题吗?我见过这个,但它很旧: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/4f634d8f-1281-430b-b664-ec7ca413b387/

Pab*_*lla 3

最后,问题出在可序列化事务中的死锁,与 id 的创建无关。

在这里我解释一下问题: http://pablocastilla.wordpress.com/2012/01/19/deadlocks-in-serialized-transactions-with-sql-server/