Loading Child Entities With Deferred Loading Turned Off

If you have a situation where you do not want to risk your code making too many database calls without you knowing about it. You have the ability to turn off deferred loading by setting DefferedLoadingEnabled to false. However when you set it to false, you loose the ability to fetch that object or collection of objects anymore. What you can do is take control of loading those child entities in your query explicitly. Let's look at an example where deferred loading is turned off and the results you get when you access the child collection.

image

image

  In the above example, I have turned off deferred loading. As a result when I try to access the Orders collection, I get a value of 0 because no orders gets loaded from the database. However if I were to modify my query by returning anonymous type, I force the query to be loaded before hand.

image

image

From the above example, you would notice that I am creating an anonymous type in which I am referencing both Customer and orders at the same time. This forces the linq to SQL to fetch both customer and its orders. Another more easier way to accomplish loading would be using DataLoadOption. It is a hint that tells linq to SQL what additional options to load when you run a particular query. In this case we would tell linq to SQL load orders for the customer when you are fetching the customer. Here is an example of the code.

 image

No Comments