How to wrap Entity Framework to intercept the LINQ expression just before execution?

Viewed 14990

I want to rewrite certain parts of the LINQ expression just before execution. And I'm having problems injecting my rewriter in the correct place (at all actually).

Looking at the Entity Framework source (in reflector) it in the end comes down to the IQueryProvider.Execute which in EF is coupled to the expression by the ObjectContext offering the internal IQueryProvider Provider { get; } property.

So I created a a wrapper class (implementing IQueryProvider) to do the Expression rewriting when the Execute gets called and then pass it to the original Provider.

Problem is, the field behind Provider is private ObjectQueryProvider _queryProvider;. This ObjectQueryProvider is an internal sealed class, meaning it's not possible to create a subclass offering the added rewriting.

So this approach got me to a dead end due to the very tightly coupled ObjectContext.

How to solve this problem? Am I looking in the wrong direction? Is there perhaps a way to inject myself around this ObjectQueryProvider?

Update: While the provided solutions all work when you're "wrapping" the ObjectContext using the Repository pattern, a solution which would allow for direct usage of the generated subclass from ObjectContext would be preferable. Hereby remaining compatible with the Dynamic Data scaffolding.

3 Answers
Related