Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

I have been investigating transactions and it appears that they take care of themselves in EF as long as I pass false to SaveChanges() and then call AcceptAllChanges() if there are no errors:

SaveChanges(false); // ... AcceptAllChanges(); 

What if something goes bad? don't I have to rollback or, as soon as my method goes out of scope, is the transaction ended?

What happens to any indentiy columns that were assigned half way through the transaction? I presume if somebody else added a record after mine before mine went bad then this means there will be a missing Identity value.

Is there any reason to use the standard TransactionScope class in my code?

like image 613
mark smith Avatar asked May 02 '09 20:05

mark smith


People also ask

Is SaveChanges a transaction?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.

What is AcceptAllChanges?

The AcceptAllChanges method is useful in the scenario where a transaction has failed and a user wants to retry.

What does the Dbcontext SaveChanges () method return?

Returns. The number of state entries written to the underlying database.


2 Answers

With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful.

The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

I.e. something like this (bad):

using (TransactionScope scope = new TransactionScope()) {     //Do something with context1     //Do something with context2      //Save and discard changes     context1.SaveChanges();      //Save and discard changes     context2.SaveChanges();      //if we get here things are looking good.     scope.Complete(); } 

If context1.SaveChanges() succeeds but context2.SaveChanges() fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1, so you can't replay or effectively log the failure.

But if you change your code to look like this:

using (TransactionScope scope = new TransactionScope()) {     //Do something with context1     //Do something with context2      //Save Changes but don't discard yet     context1.SaveChanges(false);      //Save Changes but don't discard yet     context2.SaveChanges(false);      //if we get here things are looking good.     scope.Complete();     context1.AcceptAllChanges();     context2.AcceptAllChanges();  } 

While the call to SaveChanges(false) sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager if you want.

This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager somewhere.

See my blog post for more.

like image 110
Alex James Avatar answered Sep 18 '22 19:09

Alex James


If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

use context.Database.BeginTransaction.

From MSDN:

using (var context = new BloggingContext())  {      using (var dbContextTransaction = context.Database.BeginTransaction())      {          try          {              context.Database.ExecuteSqlCommand(                  @"UPDATE Blogs SET Rating = 5" +                      " WHERE Name LIKE '%Entity Framework%'"                  );               var query = context.Posts.Where(p => p.Blog.Rating >= 5);              foreach (var post in query)              {                  post.Title += "[Cool Blog]";              }               context.SaveChanges();               dbContextTransaction.Commit();          }          catch (Exception)          {              dbContextTransaction.Rollback(); //Required according to MSDN article              throw; //Not in MSDN article, but recommended so the exception still bubbles up         }      }  }  
like image 31
user3885816 Avatar answered Sep 21 '22 19:09

user3885816