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

mas*_*tan 3 .net c# 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";

}
Run Code Online (Sandbox Code Playgroud)

此案例数据库B未获得更新.这是更新多个数据库的正确方法吗?

两者都是独立的数据库以及如何在这种情况下实现TransactionScope?

Rui*_*mba 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();
}
Run Code Online (Sandbox Code Playgroud)

此示例来自此博客文章:

使用实体框架管理事务4

  • 我相信在DbContext中不存在SaveChanges(withParameter),只有ObjectContext,它们是不同的类. (4认同)