SaveChanges has custom atomic UPDATE instructions ()

c# dapper entity-framework savechanges transactions


I need to be able to do multiple unique SQL queries for a variety of reasons.UPDATE instructions when I callSaveChanges on aDbContext . I would want for this to occur atomically, so either both the normalSaveChanges and either the SQL runs successfully or it doesn't.

But I'm not sure how to go about doing this. I've tried this and a few versions thus far:

Gist of EF transactions

Here's where there's a mistake:ExecuteSqlCommand call):

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

Fair enough, I guess. TheExecuteSqlCommand yet lacks an overload that will accept a transaction. I then replaced the problematic line with this Dapper call after installing the Dapper package, and the transaction was successful:

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

nonetheless, the issue now appears onbase.SaveChanges() I get the following as a result:

SqlConnection does not support parallel transactions.

Apparently thenSaveChanges despite the fact that I've previously made one on the connection to the datacontext, always produces a new transaction?

Exists a means through which I may achieve my goals?

Entity Framework 5.0 Code First is what I'm utilizing.

11/3/2012 12:02:26 AM

Accepted Answer

Wrap aTransactionScope surrounding all activities. The standard abstraction for.NET transactions is this class. EF andSqlConnection 's will automatically enroll. Though there are certain hazards like unintentionally starting distributed transactions, make cautious to search for best practices.

11/2/2012 11:37:23 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow