2

I'm using the following code snippet to update an entity of one DataContext

// Mark the customer as updated.
context.UpdateObject(customerToChange);
// Send the update to the data service.
context.SaveChanges();

My problem however is, that I have multiple DataContexts.

For example, if I have DataContext A and B and save the changes also in this order.

Then the Behaviour right now is: If A succeeds and B fails, then it aborts. But the changes are already persisted to A!

Wished Behaviour: If A succeeds and B fails it should also rollback A.

So my idea would be something like this:

using(TransactionScope tran = new TransactionScope()) {
    contextA.updateObject(objA);
    contextB.updateObject(objB);
    tran.Complete();
}

However, this seems not to be possible across multiple data contexts.

Do you have any ideas of how to implement this correctly with OData?

Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
  • Do these datacontext represent same database or different database? – Sameer Feb 18 '16 at 13:46
  • TransactionScope should work, if you save changes before completing the transaction and enabling MSDTC on client and server if each context represent different db connections. – Sameer Feb 18 '16 at 13:52
  • @Sameer Always the same database. There is always one DataContext per table. I can't change the architecture (It's Navision) but that shouldn't concern you. My only concern is of how to implement this properly across multiple datacontexts without changing anything else (Given the simplified scenario above). – Fabian Bigler Feb 18 '16 at 13:52

1 Answers1

0

You can try this:

Please find the ref: Using Transactions or SaveChanges(false) and AcceptAllChanges()?

    using (TransactionScope scope = new TransactionScope())
    {
    //Do something with contextA
    //Do something with contextB

   //Save Changes but don't discard yet
    contextA.SaveChanges(false);

   //Save Changes but don't discard yet
   contextB.SaveChanges(false);

   //if we get here things are looking good.
   scope.Complete();
   contextA.AcceptAllChanges();
   contextB.AcceptAllChanges();

    }
Community
  • 1
  • 1
VCody
  • 506
  • 3
  • 12
  • 1
    Thanks for your help. However, the class DataServiceContext does not provide the functions either SaveChanges(false) or AcceptAllChanges(). – Fabian Bigler Feb 18 '16 at 14:53