在Entity Framework 4.1中使用TransactionScope的多个dbcontext的SaveChanges()

时间:2012-12-14 08:50:14

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

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

数据库objAdbContext

A 数据库objBdbContext

B

更新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?

1 个答案:

答案 0 :(得分:6)

试试这个:

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