Skip to content

Instantly share code, notes, and snippets.

@baio
Last active December 20, 2015 13:29
Show Gist options
  • Save baio/6139319 to your computer and use it in GitHub Desktop.
Save baio/6139319 to your computer and use it in GitHub Desktop.
{
"title": "EF .Include, why important?",
"visbility": "public"
}

" Since compiling a LINQ query is a time-consuming process, we don’t want to do it every time we need to fetch data from the database. " See Performance Considerations for Entity Framework 5

EF 5.0 featured "Autocompiled Queries", so your queries compilation will be cached every time when query executed, but there is exceptions, one of them : Linking your query to another query that requires to be recompiled.

So every time you use joins or any other compound queries (this is when you require entities with referenced properties) query plan doesn't cached. It is clear for any project, the compound queries is more often used than not, so we need scheme which allows use these queries and plan caching. The solution here is to use Include method of ObjectQuery, this method allow to load referenced entities in a single query and generate query plan which already contains all joined references, which in turn allow query plan to be cached.

Example for compound requests (joins):

//Not using Include
var subject = context.Subjects;
var tags = q.SelectMany(p => p.Tags).ToArray(); //query plan not cached, since linking one query to another (still one request to server).

//Using Include
var subject = context.Subjects.Include("Tags");
var tags = q.SelectMany(p => p.Tags).ToArray(); //query plan cached, one requests to server!

Example for separted requests (no joins):

//Not using Include
var subject = context.Subjects.ToArray();
var tags = q.SelectMany(p => p.Tags).ToArray(); //for each subject here, will be executed another query to server to retrieve Tags

//Using Include
var subject = context.Subjects.Include("Tags").ToArray();//allready retrieve all tags referenced by Subjects and cached it to Context
var tags = q.SelectMany(p => p.Tags).ToArray(); //all tags will be retrieved from Context, no requests to server!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment