Partilhar via


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.

Comments

  • Anonymous
    March 23, 2009
    PingBack from http://blog.a-foton.ru/index.php/2009/03/24/tip-6-when-and-how-to-use-eager-loading/

  • Anonymous
    March 25, 2009
    Hopefully if you're reading this you've noticed that I've started a series of Tips recently. The Tips

  • Anonymous
    May 09, 2009
    I would just offer a caution in these types of queries.Include can be bad if the related end is an entityreference because that would cause reduandant data for each row in entitycollection.consider using include as last operation cuz depending on the query it might silently get dropped. Zeeshan

  • Anonymous
    August 24, 2010
    I would really like that incude-statement became type-safe (via for example lambda expressions) in the next version. I've seen extension methods doing the job, but this should really be supported by EF.

  • Anonymous
    June 08, 2011
    JH1984, do you have any links for the strongly typed extensions?