【问题标题】:SaveChanges() for multiple dbcontext with TransactionScope in Entity Framework 4.1SaveChanges() 用于实体框架 4.1 中带有 TransactionScope 的多个 dbcontext
【发布时间】:2012-12-14 08:50:13
【问题描述】:

我正在使用SaveChanges() 方法,如下所示:

数据库AobjAdbContext

数据库BobjBdbContext

如下所示更新 DB A 的表

public string SaveA()
{

//Some stuff

  objAdbContext.SaveChanges();

  string result=UpdateDatabaseB(some parameters)

  //Some stuff

}


public string UpdateDatabaseB(some parameters)

{

  //Some stuff

   objBdbContext.SaveChanges();

  return "Success";

}

这种情况下,数据库 B 没有更新。更新多个数据库的方法是否正确?

都是独立的数据库,这种情况下如何实现TransactionScope?

【问题讨论】:

  • 好的格式是你的朋友。

标签: c# .net entity-framework entity-framework-4 asp.net-mvc-3-areas


【解决方案1】:

试试这个:

using (TransactionScope scope = new TransactionScope())
{
    // Save changes but maintain context1 current state.
    context1.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Save changes but maintain context2 current state.
    context2.SaveChanges(SaveOptions.DetectChangesBeforeSave);

    // Commit succeeded since we got here, then completes the transaction.
    scope.Complete();

    // Now it is safe to update context state.
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();
}

此示例取自这篇博文:

Managing Transactions with Entity Framework 4

【讨论】:

  • 我相信DbContext中不存在SaveChanges(withParameter),只有ObjectContext,它们是不同的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-24
  • 2016-01-30
  • 2020-10-15
  • 1970-01-01
相关资源
最近更新 更多