Thursday, March 08, 2012

EF Eager Loading Using Include()

Setup for this post

(if you want to run the code as displayed)

Lazy Loading is cool; you don’t have to load things you don’t need. However, each item you load is more expensive for each item you load; it can be a net saving if you can avoid loading enough unneeded data.

If you, the smart human, knew that you need to load that data, wouldn’t it be nice to tell the Entity Framework to go ahead and get the data NOW. I can tell EF to Eager Load specific related tables with the Include method. All I have to do is pass in the name of the navigator property of the related object you would like to load.

NOTE: LINQPad 4 is good at displaying the results of these queries in a way that may help you visualize what is happening. I spent a good amount of time trying to include that display: it was ugly.

For example, if I ran this query (LINQPad: C# Expression):

from s in stores.Include("sales")
    select s

This query would fetch all the stores and related sales.

If I wanted to load more than related object I could chain includes like this:

from s in stores.Include("sales").Include("discounts")
    select s

I get all the stores, related sales and discounts.

If I wanted to load related objects to related objects I would put a dot (".") between each level of related objects like this:

from d in discounts.Include("store.sales")
    select d

Here I get the discounts and the stores and the sales per store; the sales will appear below the stores.

2 comments:

egmfrs said...

.Include() does not work in LINQPad 5 - I can't find a way

Jack Stephens said...

@egmfrs Include is a Entity Framework feature. In LINQPad I would add an "Entity Framework" connection that would point to the DLL (and config file) that held the model.
I remember querying the EF model in LINQPad in place of running SQL queries. That was over 5 years ago. As far as I know, that feature could be no more.