Similar to the question answered here https://stackoverflow.com/a/42932812/1321510 we need to execute a raw sql query. For the query we don't have any db context model (so any .FromSql
answers won't work for us). However we need to execute it within an existing transaction (created with context.Database.BeginTransaction()
). All solutions found on SO do not work with existing transactions.
Example:
var connection = context.Database.GetDbConnection();
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
var executeReader = command.ExecuteReader();
var values = new object[executeReader.FieldCount];
if (!executeReader.Read())
{
return values;
}
executeReader.GetValues(values);
return values;
}
}
Commiting the transaction then throws System.InvalidOperationException: 'This MySqlConnection is already in use. See https://fl.vu/mysql-conn-reuse'
.
The provided link in the exception doesn't seem helpful at all, since we're neither using async nor using the connection whilst reading from it.
We're using Pomelo.EntityFrameworkCore.MySql
as the database connector.