mysql The transaction associated with this command is not the connection’s active transaction
程序员文章站
2022-04-15 18:37:39
...
Code Fix: Set MySqlCommand.Transaction
ADO.NET example
using (var connection = new MySqlConnection(...))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT ...";
// *** ADD THIS LINE ***
command.Transaction = transaction;
// otherwise, this will throw System.InvalidOperationException: The transaction associated with this command is not the connection's active transaction.
command.ExecuteScalar();
}
}
Dapper Example
using (var connection = new MySqlConnection(...))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
// this will throw System.InvalidOperationException: The transaction associated with this command is not the connection's active transaction.
connection.Query("SELECT ...");
// use this instead:
connection.Query("SELECT ...", transaction: transaction);
}
}