SaveChanges vs. AcceptAllChanges in Entity Framework

c# entity-framework


What's the difference between, _context.SaveChanges and _context.AcceptAllChanges(), is the AcceptAllChanges() is sort of reloading data from Database or rolling back (discarding) changes made by the user when he didn't use SaveChanges()

7/16/2014 9:05:48 AM

Accepted Answer

ObjectContext.AcceptAllChanges Method - MSDN

If the SaveChanges method was called and the AcceptAllChangesAfterSave was not specified, the user must call the AcceptAllChanges method. The AcceptAllChanges method is useful in the scenario where a transaction has failed and a user wants to retry.

You may see this:

If you call SaveChanges() or SaveChanges(true),the EF simply assumes that if its work completes okay, everything is okay, so it will discard the changes it has been tracking, and wait for new changes.

Unfortunately though if something goes wrong somewhere else in the transaction, because the EF discarded the changes it was tracking, we can’t recover.

This is where SaveChanges(false) and AcceptAllChanges() come in.

SaveChanges(false) tells the EF to execute the necessary database commands, but hold on to the changes, so they can be replayed if necessary.

Now if the broader transaction fails you can retry the EF specific bits, with another call to SaveChanges(false). Alternatively you can walk through the state-manager to log what failed.

Once the broader transaction succeeds, you simply call AcceptAllChanges() manually, and the changes that were being tracked are discarded.

10/12/2012 12:42:18 PM

Popular Answer

From the Accessing Data with Microsoft .Net Framework 4 book:

When working with the Entity Framework, the submission of changes to the database is automatically handled within a transaction when you call the SaveChanges method on the ObjectContext object. Also, the AcceptAllChanges method is automatically called if no exception is thrown when updating, which will reset the state of all objects to Unchanged. Although the SaveChanges method is executed within a transaction, you might need to create your own transaction if you need to perform other operations within the same transaction

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