当SaveChanges()不成功时,如何撤消更改?

时间:2010-06-23 13:11:28

标签: c# .net entity-framework entity undo

如何在SaveChanges()不成功时撤消更改?

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

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

在这个示例中,我想删除内存中的新Toto对象。我不想手动删除它。我想将contextObject同步到我的数据库。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

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");
}