Is there a way to use TransactionScope with an existing connection?

前端 未结 3 1696
别跟我提以往
别跟我提以往 2020-12-10 03:04

I have some code that works like the advised use of TransactionScope, but has an ambient connection instead of an ambient transaction.

Is there a way to use a Transa

相关标签:
3条回答
  • 2020-12-10 03:11

    In fact, there is one way.

    connection.EnlistTransaction(Transaction.Current)
    

    It works and it doesnt promote transaction to distributed if not necessary (contrary to what documentation says)

    HTH

    0 讨论(0)
  • 2020-12-10 03:13

    To enlist a connection into a TransactionScope, you need to specify 'Enlist=true' in its connection string and open the connection in the scope of that TransactionScope object.

    You can use SqlConnection.BeginTransaction on an existing connection.

    Update: Can you use BeginTransaction like this:

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
    
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;
    
        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");
    
        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;
    
        ...
        ...
    
    }
    
    0 讨论(0)
  • 2020-12-10 03:22

    After more research, the answer to my question turned out to be:

    No, the connection needs to be opened after the TransactionScope object is instantiated.

    0 讨论(0)
提交回复
热议问题