欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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);
    }
}
相关标签: ASP.NET Core MySql