代码执行到 commandExecuteReaderAsync 就报错The transaction associated with this command is not the connections active transaction;
这个错误通常是因为在执行 command.ExecuteReaderAsync() 之前没有启动或激活事务。当使用事务时,必须先通过 connection.BeginTransaction() 来启动事务,然后通过 command.Transaction = transaction 将事务与命令关联起来。
下面是一个示例代码,展示了如何正确地启动事务并执行命令:
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
var transaction = connection.BeginTransaction();
try
{
using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "SELECT * FROM YourTable";
using (var reader = await command.ExecuteReaderAsync())
{
// 处理查询结果
}
}
// 在此处提交事务
await transaction.CommitAsync();
}
catch (Exception ex)
{
// 发生异常时回滚事务
await transaction.RollbackAsync();
throw;
}
}
在上面的示例中,我们首先通过 connection.BeginTransaction() 启动了一个事务,并将其赋值给 command.Transaction。然后,我们执行查询命令 command.ExecuteReaderAsync() 来获取查询结果。在查询完成后,我们可以选择在适当的地方调用 transaction.CommitAsync() 来提交事务。如果发生异常,我们可以通过调用 transaction.RollbackAsync() 来回滚事务。
确保在使用事务时正确地启动、激活和提交/回滚事务,以避免出现类似的错误。
原文地址: https://www.cveoy.top/t/topic/jeBR 著作权归作者所有。请勿转载和采集!