Entity-framework – How to precompile an Entity Framework Code-First Query

ef-code-firstentity-frameworkentity-framework-4.1

I am encountering some performance problems with my Entity Framework Code-First queries and I believe that precompilation may be the answer. If I were using "normal" Entity Framework, I would simply use the CompiledQuery.Compile method to precomiple my queries. But since I have a DbContext and not an ObjectContext, I can't get this to work.

I do realize that DbContext is an IObjectContextAdapter, which gives me access to the ObjectContext, but I cannot find the method that lets me get an IQueryable from my object context that works in my precompiled query. I tried to use CreateObjectSet, but when EF tried to run the query it complained that it couldn't convert that method into SQL.

So what is the best way to precompile LINQ queries against a Code-First DbContext?

Best Answer

This will be probably solved in EFv4.2 EF vNext (currently in the very first CTP) by auto-compiled LINQ queries.