Link
With the Entity Framework most of the timeSavechanges ()Is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes thoughSavechanges (false) + acceptallchanges ()Pairing is useful.
The most useful place for this is in situations where you want to do a Distributed Transaction Processing SS 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 ();}
IfContext1.savechanges ()SucceedsContext2.savechanges ()Fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes onContext1, So you can't replay or wait tively 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 callSavechanges (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 interrogateObjectstatemanagerIf you want.
This means if the transaction actually aborts you can compensate, by either re-trying or logging state of each contextsObjectstatemanagerSomewhere.
See my blog post for more.
Entity Framework-using transactions or savechanges (false) and acceptallchanges ()?