Lazy Loading child entities in Entity Framework

It's pretty interesting to see different implementations of lazy loading in both linq to SQL and entity framework. In linq to SQL, if you want to access the Orders collection of a particular customer, all you do is navigate to the Orders Collection Property and linq to SQL will run the SQL in the background and fetch the orders for that customer instance. The operation is pretty implicit. However in entity framework you have to explicitly tell that I intent to load the orders of the customer. The way you would do this is by calling Load on the Orders collection of the customer. If you forget to call load on the Orders Collection for the customer, you would end up with an empty collection of orders. This may be confusing and hard to troubleshoot bug and you would wonder why you have no orders for that customer when you could see orders in the database for the customer. Here is an example that illustrates this behavior.

image

image

In the above code, I am fetching the orders for alfki customer and printing it to the console. All that was required was simply to navigate to the Orders property and linq to SQL runs the query in the background and gets the orders for the customer. When I try to do the same thing with entity framework, it does not work. You can see that first time I try to print the orders for the customer using entity framework, I get a 0 count and that is because I have not explicitly told entity framework that I want orders for that customer.  Next time around I call Orders.Load which ensures that orders for the customer are loaded and sure enough after that when I access the orders collection I get 6 Orders.

No Comments