Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>With the Entity Framework most of the time <code>SaveChanges()</code> is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.</p> <p>Sometimes though the <code>SaveChanges(false) + AcceptAllChanges()</code> pairing is useful.</p> <p>The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.</p> <p>I.e. something like this (bad):</p> <pre><code>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(); } </code></pre> <p>If <code>context1.SaveChanges()</code> succeeds but <code>context2.SaveChanges()</code> fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on <code>context1</code>, so you can't replay or effectively log the failure.</p> <p>But if you change your code to look like this:</p> <pre><code>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(); } </code></pre> <p>While the call to <code>SaveChanges(false)</code> 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 <code>ObjectStateManager</code> if you want.</p> <p>This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts <code>ObjectStateManager</code> somewhere.</p> <p>See <a href="http://twitter.com/adjames" rel="noreferrer">my</a> <a href="http://blogs.msdn.com/alexj/archive/2009/01/11/savechanges-false.aspx" rel="noreferrer">blog post</a> for more.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload