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);
}

posted @ 2009-07-24 13:28  周宏伟  阅读(188)  评论(0编辑  收藏  举报