How can I add an interceptor to a single query in Entity Framework?

entity-framework entity-framework-6 interceptor


I have a query that I suspect is guilty of parameter-sniffing. I'd like to apply an interceptor like the one found here, but I don't want any other queries affected.

The code used there is: DbInterception.Add(new OptionRecompileHintDbCommandInterceptor());

What is the scope of this command and how do you limit the scope of an interceptor to just a single query?

My first thought was to do something like this:

var interceptor = new OptionRecompileHintDbCommandInterceptor();

    // Do query

But is this same to do or could it affect queries on other threads?

Update Another thought occurred to me. If I can't control when an interceptor is applied, is there a way to put the logic in a conditional if statement in the interceptor and then supply some kind of context to the interceptor so it knows when to apply the logic?

5/23/2017 12:32:17 PM

Accepted Answer

Two options I can think of for this, since it is at the global level, is in the query you want to single out, you can do something where you say 9 = 9 or something that is always true so you know it is the query you want. Then you could find and replace that where clause part with an empty string and then continue on with whatever you were going to do.

The other is quite a bit sneakier, but should work. In your interceptor code, you can do this:

var ctx = interceptionContext.DbContexts.FirstOrDefault() As MyDbContext;

But then you should be able to cast it to your specific DbContext type. On that DbContext type, you could just add some boolean property that would indicate this is the query you are running. Then, right before running it, you can set that to true wherever else and you'd be able to intercept it.

3/28/2017 5:36:06 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow