Tip 6 - How and when to use eager loading

When should you use eager loading?

Usually in your application you know what you are going to "do" with an entity once you have retrieved it.

For example if you retrieve an order so you can re-print it for a customer, you know that the re-print would be incomplete without information about the items and products that make up that order, so you know you are going to need to load this information too.

This is the sort of situation where eager loading is useful.

If you know you need extra information, or entities, you might as well load those entities in advance (eager loading), because it will save you queries later.

How do you do eager loading?

Well contrary to some commonly held misconceptions, eager loading is both possible and easy with the Entity Framework, you simply use the Include() method to boot-strap your query like this:

var reprint = (from order in ctx.Orders.Include("Items.Product")
             where order.Customer.Name == "Fred Blogs"
&& order.Status == "Unshipped"
             select order).First();

This query says with each order that matches the query include its "Items" and with each item include its "Product" too.

The result is that this code:

foreach (var item in reprint.Items)
{
    Console.WriteLine("\t{0} {1} = ${2}",
        item.Quantity,
        item.Product.Name,
        item.Cost);
}

Console.WriteLine(reprint.TotalCost);

... requires no new queries.

NOTE:  
There is no need to Include("Items") explicitly, the call to Include("Items.Product") implicitly includes the items.