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

我的梦境 提交于 2019-11-28 09:52:42

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

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;

    ...
    ...

}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!