Can I get a reference to a pending transaction from a SqlConnection object?

后端 未结 6 524
無奈伤痛
無奈伤痛 2020-12-30 18:51

Suppose someone (other than me) writes the following code and compiles it into an assembly:

using (SqlConnection conn = new SqlConnection(connString)) 
{
            


        
6条回答
  •  灰色年华
    2020-12-30 19:52

    The command object can only be assigned a transaction object using one of its constructors. You can go for the .NET 2.0 approach and use a TransactionScope object which is defined in the System.Transactions namespace (has a dedicated assembly).

       using System.Transactions;
    
        class Foo
        {   
            void Bar()
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    // Data access
                    // ...
                    scope.Complete()
                }
            }
        }
    

    The System.Transactions approach uses in conjunction with SQL Server 2005 a lightweight transaction coordinator (LTM). Be careful not to use multiple connection objects in your transaction scope or the transaction will get promoted as it is seen as distributed. This more resource-intensive version of the transaction will then be handled by DTC.

提交回复
热议问题