AcceptAllChanges and SaveChanges methods in Entity Framework

The default behavior of SaveChanges() method is when a transaction is executed successfully, it calls DetectChangesBeforeSave() and AcceptChangesafterSave() methods automatically. This automatic calling happens only if we have not passed any values to the SaveChanges() method.

The statement ctx.SaveChanges(); is equivalent to ctx.SaveChanges(SaveOptions.DetectChangesBeforeSave | SaveOptions.AcceptChangesAfterSave);
The SaveChanges() method takes an enum of type SaveOptions. The enum can have three possible values. Either we can send a single value to this method or we can combine the values and send as shown above. The possible ways we can call the SaveChanges() method are:

1.ctx.SaveChanges(AcceptChangesafterSave); - The AcceptAllChanges method is invoked after persistence happens to the database (INSERT and UPDATE commands are executed depending on the state of entities) and all the entities which are in added and modified states are changed to UnChanged state. Because the AcceptAllChanges() method resets the object state to Unchanged, if we want to explicitly call this function, we should call it only after entities persist (after data is saved). Otherwise changes are not saved to the database.

2.ctx.SaveChanges(DetectChangesBeforeSave); - calls the DetectChanges method before saving changes and synchronization happens between entities and ObjetctStateManager entries. In the article, Snapshot Change Tracking using DetectChanges(), importance of calling DetectChanges when we are using POCOs is explained.

ctx.DeleteObject(selectedcustomer); ctx.SaveChanges(SaveOptions.DetectChangesBeforeSave);

code snippet for SaveChanges method

3.ctx.SaveChanges(None); neither DetectChanges nor AcceptAllChanges methods are called.

Understanding AcceptAllChanges and SaveChanges in a transaction
EF maintains transactions implicitly. When we call SaveChanges() method, the ObjectContext starts the transaction and commits the changes. If any operation fails, rollback occurs. Consider the following example. If the default transaction is successful (entities are persisted successfully), both the DetectChanges and AcceptAllChanges methods are called. However, we can change this default behavior by passing SaveOptions enum to SaveChanges() as we have seen earlier in this article.

code snippet for SaveChanges method in a transaction