Interception in Entity Framework Core
Right now, Entity Framework Core still does not have all of the features provided by pre-Core versions, I even wrote a post about this. One of this features is the ability to intercept queries, something that was provided by the IDbCommandInterceptor, IDbCommandTreeInterceptor interfaces.
What we have in EF Core 2.0 is interception at the SQL level, and we can only get to this in a rather convoluted way, through the DiagnosticSource mechanism (yes, I do intend to write about it!). So, let’s create a class with three methods, like this:
public class CommandListener
{
[DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting")]
public void OnCommandExecuting(DbCommand command, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime)
{
}
[DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandExecuted")]
public void OnCommandExecuted(object result, bool async)
{
}
[DiagnosticName("Microsoft.EntityFrameworkCore.Database.Command.CommandError")] public void OnCommandError(Exception exception, bool async) { }
}
var listener = ctx.GetService<DiagnosticSource>();
(listener as DiagnosticListener).SubscribeWithAdapter(new CommandListener());