开发者

Keeping DomainContext up to date on SubmitOperation failure

开发者 https://www.devze.com 2023-04-11 16:33 出处:网络
Background: Silverlight 4 - RIA - Entity Framework 4 Description: I have some deletion code in which I do:

Background: Silverlight 4 - RIA - Entity Framework 4

Description: I have some deletion code in which I do:

db.Items.Remove(selectedItem);
db.SubmitChanges(deleteItemOperationCompleted, null);

Here the item is removed from the domain context and then the service attempts to perform the operati开发者_如何学Pythonon on the EF (which in turn performs the operation on the DB).

The callback method:

private void deleteOperationCompletedM(SubmitOperation op)
{
    if (op.Error == null)
    {
        MessageBox.Show("Delete operation was successfull.");
        // Some other code here (removed for brevity)
    }
    else
    {
        op.MarkErrorAsHandled();
        MessageBox.Show("An error has occured." + op.Error.Message);
    }
}

Repro: I try to delete the item (which can NOT be deleted because of the referential integrity constraint in the database). I receive the message that the error has occured. That's ok. When I then try to delete some other item (which is not related by foreign key to any other entity), I receive the same message, even though this item can be removed from the database.

The problem is that I have removed the first item from the domain context (even though it was not deleted from the database). So when I try to delete the second item, it is also removed from the context. When submiting the changes, the last item could be deleted from the DB, but the problem is that the changes are submitted for the whole context, and since in the first step I have removed an item that can't be deleted from the DB, the submit operation fails.

Question: What is the right way (best practice) to "rollback" the operation in the case of the submit failure? The only think I can think of is to create another domain context and to load the data again, but I'd like to avoid that because of the amount of data loaded. Can the context be returned to some previous state or cancel pending changes? How to approach this problem?


In your case, you should call RejectChanges on your DomainContext to cancel the deletion of the item and to change its EntityState back to Unmodified.

private void deleteOperationCompletedM(SubmitOperation op) {
  if (op.Error == null) {
    MessageBox.Show("Delete operation was successfull.");
    // Some other code here (removed for brevity)
  }
  else{
    op.MarkErrorAsHandled();
    MessageBox.Show("An error has occured." + op.Error.Message);

    db.RejectChanges();  // call reject changes on the DomainContext
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号