When would you use SaveChanges(false) + AcceptAllChanges()?

Technology CommunityCategory: Entity FrameworkWhen would you use SaveChanges(false) + AcceptAllChanges()?
VietMX Staff asked 3 years ago

With the Entity Framework most of the time SaveChanges() is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.

Consider:

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 call to SaveChanges(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 interrogate the ObjectStateManager if you want.