【问题标题】:Entity Framework SaveChanges(False) fails while using TransactionScope使用 TransactionScope 时实体框架 SaveChanges(False) 失败
【发布时间】:2013-01-08 19:47:16
【问题描述】:

在以下链接上提出的问题也有一个很好的答案,但我的问题从那之后开始。

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

我尝试了按照我的要求给出的代码如下


MyEntities context1 = new MyEntities();

...
...
 // some code for changing the table data in Context 1.
...

MyEntities context1 = new MyEntities();

using (TransactionScope scope = new TransactionScope())
{
    context1.SaveChanges(false);   // LABEL 1
    context2.SaveChanges(false);   // LABEL 2
    scope.Complete();             // LABEL 3
    context1.AcceptAllChanges();  // LABEL 4
    context2.AcceptAllChanges();  // LABEL 5
}

在标有 // LABEL 1 的行之前一切正常 但是在 // LABEL 2 线上它没有说 “底层提供商在 Open 上失败。”

注意:- 请注意 Context1、Context2 是相同类型的 2 个不同实例。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 调试任何东西的第一步是查看完整的错误消息。查看内部异常。

标签: entity-framework transactionscope savechanges


【解决方案1】:

此答案可能会解释您的问题的原因: https://stackoverflow.com/a/3081776/655625 您可能需要在 context1.SaveChanges(false); 行之后重新打开连接。 如:

context2.Database.Connection.Open(); //before the second SaveChanges(false)

但是,仔细阅读,您会发现您正在以这种方式进行分布式事务,另一个答案(与第一个答案相关)显示了避免分布式事务的替代方法(更详细)。 https://stackoverflow.com/a/794785/655625

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多