Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SaveChanges vs. AcceptAllChanges in Entity Framework

Tags:

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()

like image 617
S3ddi9 Avatar asked Oct 12 '12 12:10

S3ddi9


1 Answers

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: http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx

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.

like image 164
Habib Avatar answered Sep 21 '22 17:09

Habib