我正在使用以下代码片段来更新一个 DataContext 的实体
// Mark the customer as updated.
context.UpdateObject(customerToChange);
// Send the update to the data service.
context.SaveChanges();
但是我的问题是,我有多个 DataContext。
例如,如果我有 DataContext A 和 B,并且也按此顺序保存更改。
那么现在的行为是: 如果 A 成功而 B 失败,则它中止。但是更改已经持久化到 A 了!
希望的行为: 如果 A 成功而 B 失败,它也应该回滚 A。
所以我的想法是这样的:
using(TransactionScope tran = new TransactionScope()) {
contextA.updateObject(objA);
contextB.updateObject(objB);
tran.Complete();
}
但是,这似乎无法跨越多个数据上下文。
您对如何使用 OData 正确实现它有什么想法吗?
最佳答案
你可以试试这个:
请查找引用: 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();
}
关于c# - 具有多个 DataContext 的事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35482971/