有没有一种方法可以在现有连接中使用TransactionScope?

18

我有一些代码,它的功能类似于TransactionScope的建议使用,但具有环境连接而不是环境事务。

是否可以使用现有连接对象与TransactionScope对象配合使用,或者在.NET框架中有其他替代方案可供使用?

3个回答

34

实际上,有一种方法。

connection.EnlistTransaction(Transaction.Current)

它能正常工作并且仅在必要时才会将事务推广到分布式,与文档所说的相反。

希望这有帮助。


什么是“连接”? - Muflix
1
只要是从DbConnection派生的任何类。 - Michal Levý

5
为了将连接加入到TransactionScope中,您需要在其连接字符串中指定“Enlist=true”,并在该TransactionScope对象的范围内打开连接。
您可以在现有连接上使用SqlConnection.BeginTransaction。
更新:您可以像这样使用BeginTransaction:
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;

    ...
    ...

}

事实是,在TransactionScope实例化之前,连接已经打开了;这就是我提出问题的原因。 - Nathan Ridley
@Mitch,无论在何种情况下,connection.BeginTransaction("SampleTransaction")都会升级为分布式事务(DTC)吗?如果是的话,那么有哪些情况呢? - Baig

3
经过更多的研究,我的问题的答案是:
不,连接需要在 TransactionScope 对象实例化之后打开。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接