shlomiw
shlomiw

Reputation: 365

EF "Database-First" ObjectContext and DbInterception?

Is it possible to use EF 6.0's DbInterception with Database-First ObjectContext? or is it only used via DbContext?

I couldn't get it to work with my good old (legacy) ObjectContext.

Thanks in advance, Shlomi

Upvotes: 3

Views: 1479

Answers (1)

user3319439
user3319439

Reputation:

AFAIK DbInterception is independent of whether you use Database-First or Code-First modelling.

You can just add an interceptor near the start of your application.

public class LogInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
    }

    public void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        System.Diagnostics.Debug.WriteLine(command.CommandText);
    }

    public void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
    {
    }

    public void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
    {
        System.Diagnostics.Debug.WriteLine(command.CommandText);
    }

    public void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
    }

    public void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
        System.Diagnostics.Debug.WriteLine(command.CommandText);
    }
}

Usage:

// Add an interceptor to log executed SQL queries.
DbInterception.Add(new LogInterceptor());

Upvotes: 4

Related Questions