具有多个DataContexts的事务

时间:2016-02-18 13:36:36

标签: c# transactions odata

我正在使用以下代码段来更新一个DataContext

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

我的问题是,我有多个DataContexts。

例如,如果我有DataContext A和B并按此顺序保存更改。

然后现在的行为是: 如果A成功而B失败,则中止。但是这些变化已经持续到A!

许愿行为: 如果A成功而B失败,它也应该回滚A.

所以我的想法是这样的:

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

但是,这似乎不可能跨多个数据上下文。

您对如何使用OData正确实现这一点有任何想法吗?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

请找到参考:            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();

    }
相关问题