简体   繁体   English

具有多个DataContext的事务

[英]Transactions with multiple DataContexts

I'm using the following code snippet to update an entity of one DataContext 我正在使用以下代码片段更新一个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. 但是我的问题是,我有多个DataContext。

For example, if I have DataContext A and B and save the changes also in this order. 例如,如果我有DataContext A和B,并且也按此顺序保存更改。

Then the Behaviour right now is: If A succeeds and B fails, then it aborts. 那么,现在的行为是:如果A成功而B失败,则中止。 But the changes are already persisted to A! 但是更改已经保存到A!

Wished Behaviour: If A succeeds and B fails it should also rollback A. 不良行为:如果A成功而B失败,它也应该回滚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? 您对如何使用OData正确实现这一点有任何想法吗?

You can try this: 您可以尝试以下方法:

Please find the ref: Using Transactions or SaveChanges(false) and AcceptAllChanges()? 请找到参考: 使用Transactions或SaveChanges(false)和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();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM