- To log EF standard workflow, use the
Log
property, that accepts any Action<string>
type.
using (var context = new SchoolDBEntities())
{
context.Database.Log = Console.Write;
var student = context.Students
.Where(s => s.StudentName == "Student1").FirstOrDefault();
student.StudentName = "Edited Name";
context.SaveChanges();
}
Interception
- EF provides the ability to intercept the context using
IDbCommandInterceptor.
- It intercepts before and after it performs the
ExecuteNonQuery
, ExecuteScalar
, ExecuteReader
operations to the database.
class EFCommandInterceptor: IDbCommandInterceptor
{
public void NonQueryExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<int> interceptionContext)
{
LogInfo("NonQueryExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
public void NonQueryExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<int> interceptionContext)
{
LogInfo("NonQueryExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
public void ReaderExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContextt<System.Data.Common.DbDataReader> interceptionContext)
{
LogInfo("ReaderExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
public void ReaderExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
LogInfo("ReaderExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
public void ScalarExecuted(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<object> interceptionContext)
{
LogInfo("ScalarExecuted", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
public void ScalarExecuting(System.Data.Common.DbCommand command,
DbCommandInterceptionContext<object> interceptionContext)
{
LogInfo("ScalarExecuting", String.Format(" IsAsync: {0}, Command Text: {1}",
interceptionContext.IsAsync, command.CommandText));
}
private void LogInfo(string command, string commandText)
{
Console.WriteLine("Intercepted on: {0} :- {1} ", command, commandText);
}
}
- To configure the interceptor, use config file or code-based configuration.
<entityFramework>
<interceptors>
<interceptor type="MyNameSpace.EF6CodeConfig, EntityFramework"></interceptor>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\\Temp\\LogOutput.txt" />
</parameters>
</interceptor>
</interceptors>
</entityFramework>
public class EF6CodeConfig : DbConfiguration
{
public EF6CodeConfig()
{
AddInterceptor(new EFCommandInterceptor());
}
}
Logging and intercepting database operations - EF6