Repository navigation
Description
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.InvalidOperationExceptionException:
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
thepirat000 commentedon Oct 9, 2023
I've found the issue in my
DbCommandInterceptor.When the command result has more than one result set, then using a
DataTableto consume the reader will only consume the first result set, and will leave the original data reader open.Here's the revised interceptor code: