Patrice Pezillier
Patrice Pezillier

Reputation: 4586

How can I undo changes when a SaveChanges() doesn't succeed?

How can I undo changes when a SaveChanges() doesn't succeed ?

contextObject.Toto.AddObject( new Toto());

try
{
    contextObject.SaveChanges();
}
catch
{
      // Undo changes !
}

In this sample, I'd like to remove the new Toto object in memory. I don't want to remove it manually. I'd like to synchronize my contextObject to my database.

Upvotes: 1

Views: 1754

Answers (2)

Patrice Pezillier
Patrice Pezillier

Reputation: 4586

Microsoft is working on it : Unable to refresh some items in the ObjectContext

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 75659

Saving Changes and Managing Concurrency:

try
{
    // Try to save changes, which may cause a conflict.
    int num = context.SaveChanges();
    Console.WriteLine("No conflicts. " +
        num.ToString() + " updates saved.");
}
catch (OptimisticConcurrencyException)
{
    // Resolve the concurrency conflict by refreshing the 
    // object context before re-saving changes. 
    context.Refresh(RefreshMode.ClientWins, orders);

    // Save changes.
    context.SaveChanges();
    Console.WriteLine("OptimisticConcurrencyException "
    + "handled and changes saved");
}

Upvotes: 0

Related Questions