Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I precompile an Entity Framework Code-First Query?

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?

like image 944
John Bledsoe Avatar asked Jun 21 '11 13:06

John Bledsoe


People also ask

What is compiled query in Entity Framework?

A compiled query is an object that keeps a prepared SQL statement and a delegate to a materializing function. The first one is to be executed at the server to get rows related to the query, the second one transforms a result set into a sequence of entity objects.


2 Answers

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

like image 57
Ladislav Mrnka Avatar answered Sep 29 '22 06:09

Ladislav Mrnka


As from the official announecment:

"No compiled query support from DbContext Unfortunately due to some technical limitations in the compiled query functionality we shipped in .NET Framework 4.0 we are unable to support compiled queries via the DbContext API. We realize this is a painful limitation and will work to enable this for the next release. "

Link.

like image 22
BennyM Avatar answered Sep 29 '22 08:09

BennyM