我在 C# .Net 6.0 控制台应用程序中有以下代码。问题是第一次调用此方法工作正常,但在第二次调用中,应用程序在执行 await command.ExecuteNonQueryAsync() 时崩溃。它甚至不去 catch 块。 commandText 是一个普通的更新 SQL,参数具有所有有效值。任何见解表示赞赏。
private async Task<int> ExecuteTransaction(string commandStr, SqlParameter[] parameters)
{
int rowsAffected = -1;
using (var connection = await _connectionFactory.CreateConnection())
{
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = await connection.BeginTransactionAsync() as SqlTransaction;
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = commandText;
if (parameters?.Length > 0)
{
command.Parameters.AddRange(parameters);
}
***rowsAffected = await command.ExecuteNonQueryAsync();***
// Attempt to commit the transaction.
transaction.Commit();
}
catch (Exception ex)
{
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
// Log error.
}
catch (Exception ex2)
{
// Do something.
}
}
}
return rowsAffected;
}