.net 从System.Transactions.TransactionScope获取System.Data.SqlClient.SqlTransaction
是否有一种方法可以从.net 从System.Transactions.TransactionScope获取System.Data.SqlClient.SqlTransaction,.net,sql-server,vb.net,.net,Sql Server,Vb.net,是否有一种方法可以从System.Transactions.TransactionScope或System.Data.SqlClient.SqlConnection的实例中获取System.Data.SqlClient.SqlTransaction 假设我正在使用aTransactionScope,但想将SqlTransaction传递给一些遗留代码。是否可以从TransactionScope或SqlConnection获取事务 将作用域用作TransactionScope=GetTransac
System.Transactions.TransactionScope
或System.Data.SqlClient.SqlConnection
的实例中获取System.Data.SqlClient.SqlTransaction
假设我正在使用aTransactionScope
,但想将SqlTransaction
传递给一些遗留代码。是否可以从TransactionScope
或SqlConnection
获取事务
将作用域用作TransactionScope=GetTransactionScope()
使用conn作为SqlClient.SqlConnection=GetConnection(Globals.ConnectionString)
conn.Open()'如果存在由'TransactionScope'创建的环境事务,则它将自动在事务中登记自身`
LegacyFunction(transaction)“我会尝试使用接受事务的ctor
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;
try
{
using (TransactionScope ts = New TransactionScope(transaction))
{
LegacyFunction(transaction);
....
}
transaction.Commit();
Console.WriteLine("Commit");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
除了布拉姆给出的答案之外,还有一点是-System.Transactions.TransactionScope
与IDBTransaction
是完全不同的概念。因此,您可以在BARM的回答中看到—在DbConnection对象上调用BeginTransaction时,您可以用不同的方法传递该事务对象
简而言之,您不能在遗留函数中使用TransactionScope
。为什么要在Legacyfunction中传递它??因为您的代码已经在TransactionScope块下运行。它是一个旧函数,接受System.Data.SqlClient.SqlTransaction
作为参数。我无法更改该函数,但我想使用TransactionScope
。我想我可以使用System.Transactions.Current
,但它不会返回System.Data.SqlClient.SqlTransaction
。想必您的ExecuteSQL做了一些涉及SQLCommand的事情?您是否查看了在登记时是否正在设置?TransactionScope将事务作为参数,而不是SqlTransaction