Jul 26 2007

Deferred Loading in DLinq

Category: DLinqBil@l @ 14:08

Suppose we have an entity class called Customer and it contains a property of type List of Order entity classes. Now we want to retrieve all the customers and their orders, how do we do this using Query Expression?

var results=  from c in db.Customer
  select c;

However, this will not load the orders inside the customer entities returned! Why? The reason is that DLinq uses deferred loading and is known as "lazy loading".
In the above query, we only retrieved the customer entities, but the Orders were not loaded too! This goes back to the fact that Customer class has a relation with the Order class just as the relation between Customer and Order data tables. in the database. This explains that related objects are governed by "Deferred loading". Only the main class's properties are loaded, and all related objects are not.

But, when you enumerate through the results, and when you access the Orders property, DLinq goes to the database and retrieves them without letting you know of this!

So, what if we wanted to disable Deferred Loading? You could do a projection and retrieve both elements, but then the result of the projection will be read only. This is where we use DataShape object!!

 DataShape ds = new DataShape();
 ds.LoadWith<Customer>(c => c.Orders);
 db.Shape = ds;
 var q =
  from c in db.Customers
  where c.City == "London"
  select c;

You are informing the query to load the Orders collection on the Customer class, whenever a customer entity is loaded from the database!

Hope this helps,


Comments are closed