Skip to content

Changing the result after reader executed in a DbCommandInterceptor  #31991

Closed as not planned

Description

@thepirat000

I'm trying to create a DbCommandInterceptor that logs the results from the database after any command is executed.

So I'm overriding ReaderExecuted() / ReaderExecutedAsync() in my interceptor, in order to read from the Sql Data Reader, and create a new data reader to send back to EF.

For example:

public class MyCommandInterceptor : DbCommandInterceptor
{
    public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
    {
        if (eventData.ExecuteMethod == DbCommandMethod.ExecuteReader)
        {
            // Create a data table from the original reader
            var dataTable = new DataTable();
            dataTable.Load(result);

            // Log the result from the data table
            LogResultData(dataTable);

            // Create and return a new data reader so EF can consume the result
            return dataTable.CreateDataReader();
        }

        return result;
    }

    private void LogResultData(DataTable dataTable)
    {
        var resultData = dataTable.AsEnumerable().Select(row => dataTable.Columns.Cast<DataColumn>().ToDictionary(c => c.ColumnName, c => row[c])).ToList();
        Debug.WriteLine(JsonSerializer.Serialize(resultData));
    }
}

Based on this documentation for EF6, an interceptor could change the result after execution, so I'm assuming this is still valid for EF core.

The interceptor works as expected for single inserts or updates, but I get an exception when the command contains updates to two related entities.

// 1. Insert a new client and its address (SUCCEEDS)
var entity = new Client()
{
    Name = "Client1",
    Address = new Address() { Text = "Address1" }
};
context.Add(entity);
context.SaveChanges();

// 2. Update a client  (SUCCEEDS)
entity.Name = "Client2";
context.SaveChanges();

// 3. Update an address  (SUCCEEDS)
entity.Address.Text = "Address2";
context.SaveChanges();

// 4. Update both a client and its address (FAILS)
entity.Name = "Client3";
entity.Address.Text = "Address3";

context.SaveChanges();  // Throws System.InvalidOperationException

Exception:

System.InvalidOperationException: 'There is already an open DataReader associated with this Connection which must be closed first.'

Stack Trace:

   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
   at Microsoft.Data.SqlClient.SqlInternalTransaction.Rollback()
   at Microsoft.Data.SqlClient.SqlInternalTransaction.Dispose(Boolean disposing)
   at Microsoft.Data.SqlClient.SqlInternalTransaction.Dispose()
   at Microsoft.Data.SqlClient.SqlTransaction.Dispose(Boolean disposing)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Dispose()
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__107_0(DbContext _, ValueTuple`2 t)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
   at Program.<Main>$(String[] args) in C:\Temp\EFCoreInterceptor\Program.cs:line 40

I'm attaching a minimal sample project that reproduces the issue.
EFCoreInterceptor.zip

Provider and version information

EF Core version: 7.0.11
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 7.0
Operating system: Windows
IDE: Visual Studio 2022 17.4

Activity

  1. thepirat000 commented on Oct 9, 2023

    @thepirat000
    Author

    I've found the issue in my DbCommandInterceptor.

    When the command result has more than one result set, then using a DataTable to consume the reader will only consume the first result set, and will leave the original data reader open.

    Here's the revised interceptor code:

    public class MyCommandInterceptor : DbCommandInterceptor
    {
        public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
        {
            if (eventData.ExecuteMethod == DbCommandMethod.ExecuteReader)
            {
                // Create the data set from the original reader
                var dataset = new DataSet();
                do
                {
                    var table = new DataTable();
                    table.Load(result);
                    dataset.Tables.Add(table);
                } while (!result.IsClosed);
    
                // Log the result from the data set
                LogResultData(dataset);
    
                // Return a new data reader so EF can consume the results
                return dataset.CreateDataReader();
            }
    
            return result;
        }
    
        private void LogResultData(DataSet dataSet)
        {
            var resultData = dataSet.Tables.Cast<DataTable>().AsEnumerable().Select(t =>
                    new
                    {
                        Table = t.TableName,
                        Values = t.AsEnumerable().Select(row => t.Columns.Cast<DataColumn>().ToDictionary(c => c.ColumnName, c => row[c]))
                    });
    
            Debug.WriteLine(JsonSerializer.Serialize(resultData));
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions