Editorials

Intercepting Entity Framework Database Calls

Today I have been looking at the extension in Entity Framework (EF) 6 allowing the auditing of the generated SQL and it’s execution. http://msdn.microsoft.com/en-us/data/dn469464.aspx This is built into the EF library allowing the developer to intercept, log, modify or even cancel the generated SQL code.

This can be used to solve any number of problems. If you need to trace or capture history of executed commands you could utilize EF to log the intercepted data. The output can be directed to the console, memory, a database, or even files. It connects easily to the NLog library from Microsoft.

One feature I liked about this extension is that it can intercept before or after execution. Interception before allows you to potentially modify the generated code. I think that would be more useful to a developer when creating or debugging code. If you intercept after execution the framework provides some additional statistics regarding the time to execute the query. It doesn’t include time for handling returned results , such as a loop processing a datareader. But it does tell you how long it took your database to execute the query and return control to your calling application.

The EF interfaces allow you to integrate existing or custom functions for handling the output. The output is a string, so can be re-directed to nearly anything you wish to create. This makes it straight forward to build your own custom consumer, or link into an already existing logging system.

Do you find it valuable to have the ability to inspect the performance of your ORM engine, in this case Entity Framework? There are a number of libraries performing this task, so I anticipate the answer to be yes. What problems do you solve with this sort of utility? Share your experience here or by email to btaylor@sswug.org.

Cheers,

Ben