1

For various reasons I need to be able to do several custom SQL UPDATE commands when I call SaveChanges on a DbContext. I want this to happen atomically so either both the regular SaveChanges and the SQL succeeds, or neither does.

I don't know how to accomplish this though. What I've tried so far is this and various variations:

EF transactions — Gist

The error here is (on the ExecuteSqlCommand call):

ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction.

Okay, fair enough. The ExecuteSqlCommand doesn't have an overload that accepts a transaction though. So, I installed the Dapper package and replaced the offending line with this Dapper call and I pass in the transaction:

this.Database.Connection
  .Execute("insert into Tests (Foo, Bar) values ('test', 2)", 
  transaction: tran);

but now the error happens on base.SaveChanges() and it gives me the following:

SqlConnection does not support parallel transactions.

So apparently SaveChanges always creates a new transaction even though I created one on the connection of the datacontext already?

Is there any way in which I can accomplish what I want?

I'm using Entity Framework 5.0 Code First.

4

1 回答 1

3

环绕TransactionScope所有操作。此类是 .NET 事务的通用抽象。EF 和SqlConnection's 将自动登记。请务必寻找最佳实践,因为存在一些陷阱,例如意外触发分布式事务。

于 2012-11-02T23:37:23.460 回答