3

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

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for your reply and sorry for my late reply. I tried this with normal ObjectContext (Db-First) and it didn't work. Any ideas why? (the code is pretty much similar to what you suggested).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.