代码之家  ›  专栏  ›  技术社区  ›  caryden

如果其中一个数据库是只读的,是否会发生分布式事务升级?

  •  0
  • caryden  · 技术社区  · 15 年前

    源服务器与目标服务器位于不同的服务器上。两者都是MS SQL 2008。我们使用Linq2SQL访问源,使用自定义数据层访问目标。我们从不修改源数据库(尽管我们目前不将其恢复为只读)。但是,现在,当我们在transactionScope中运行导入时,整个事务将升级为DTC,因为我们在不同的服务器上访问两个DB。

    关于如何在这种情况下避免DTC升级的任何其他建议?

    Remus回答的后续问题(再次感谢):

    后续行动#1:

    using(var scope = new TransactionScope())
    {
       // read some from source db using Linq2Sql
       // transform source info
       // update destination
    
       // read some more from source db using Linq2Sql
       // transform source info
       // update destination
    
    }
    

    您是说在TransactionScope中围绕Linq2Sql位使用RequiresNew吗?或者,我想,因为我真的不关心源代码处的事务,所以我可以用事务来处理抑制,以将该连接包含在任何事务中,对吗?

    后续行动#2:

    1. “second connection”==连接对象的第二个实例,即使它与connectionstring完全相同
    2. “第二个连接”==连接到一个单独的资源管理器,在SQL2005和之前,这意味着与上面的1相同,但在SQL2008上,这意味着一个单独的实例(即,同一实例上的两个数据库不会升级)
    1 回复  |  直到 12 年前
        1
  •  2
  •   Remus Rusanu    15 年前

    在事务作用域内打开第二个ADO.Net连接时,两个连接都将升级为DTC。即使是同一数据库的新连接,也无所谓。数据库只读也与此无关,不可能与之有任何关系。首先,连接不是特定于数据库的,因为它们可以在打开后更改数据库。其次,只读数据库可以执行大量的写入操作(例如,可以调用readonlydb.dbo.myProcedure,在该过程中,我可以更新writeabledb.dbo.table)。

    如果要避免DTC,则必须在两个访问层之间使用不同的事务作用域(即使用REQUIRE创建新的作用域)。

    // read some from source db using Linq2Sql 
    // read some more from source db using Linq2Sql 
    using(var scope = new TransactionScope()) 
    { 
       // transform source info 
       // update destination 
    
       // transform source info 
       // update destination 
    } 
    

    但我知道这是不太可能的,因为第二组读取通常取决于第一次转换/更新的结果。因此,在执行读取时,您最好将范围限制在最上面:

    using(var scope = new TransactionScope()) 
    { 
       using(var nada= new TransactionScope(TransactionScopeOption.Supress))
       {
           // read some from source db using Linq2Sql 
           // transform source info 
       }
       // update destination 
    
       using(var nada= new TransactionScope(TransactionScopeOption.Supress))
       {
           // read some more from source db using Linq2Sql
           // transform source info 
       } 
       // update destination 
    } 
    

    推荐文章