Skip to content

The extension ExecuteStoredProcedure<T> of EFCore is not working with transactions #30

@weismantelf

Description

@weismantelf

The following sample, will always throw the following exception:

ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.

       using (AlarmDBContext ctx = OpenConnection())
        {
            using (IDbContextTransaction tx = StartTransaction(ctx))
            {
                try
                {
                    var proc = new sp_GetEventAlarmsMonitorData()
                    {
                    };

                    List<EventAlarmMonitorData> result = ctx.Database.ExecuteStoredProcedure<EventAlarmMonitorData>(proc).ToList();

                    ctx.SaveChanges();

                    tx.Commit();

                    return result;
                }
                catch (Exception ex)
                {
                    logger.Error(ex, "ERROR ON GetEventAlarmMonitorData: " + ex.Message);
                    RollbackTransaction(tx);
                    throw;
                }
            }
        }

The reason is that the method ExecuteStoredProcedure of the DatabaseExtension class is not setting the transaction property of the DbCommand used by this method.

With the following change the ExecuteStoredProcedure is working:

using  Microsoft.EntityFrameworkCore.Storage;

using (var command = database.GetDbConnection().CreateCommand())
 {
    command.CommandText = info.Sql;
    command.CommandType = CommandType.Text;
    command.Parameters.AddRange(info.SqlParameters);
    command.Transaction = database.CurrentTransaction.GetDbTransaction();
    // database.OpenConnection();`
   ...
}

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions