Linq To SQL Optimizes Eager Loading

If you have read my previous blog posting about the Load operator in entity framework and how it works in terms of lazy loading object regardless if it object has been tracked earlier, you must be keen to know how does this behavior work with Linq to SQL. I must say Linq to SQL has always surprised me in terms of how efficient it is in terms of dealing with retrieving data from the database. When you lazy load a particular entity reference, Linq to SQL will first track its tracking repository to see if it can find the object there. If an object is found it by passes database and simply returns the object from its cache. This is an optimized behavior as compared to how entity framework tackles this problem. For example if I have much of orders and I want to lazy load its customer, Linq to SQL will not make a database call for every Order to get its customer. If those orders belong to a total 5 distinct customers, than only 5 database calls will be made. Below is an example that shows this behavior.

image

 image

In the above code, I am retrieving Orders shipped in the city of London and than lazy loading its customer to print the customer for each order. Although orders returned numbered to 33 but the total database calls made was 5. This is because those 33 orders belong to total of 5 customers. Linq to SQL was smart enough to use its tracking service to figure out that if it can find an object in the cache, there is no need to make a call to the database.

1 Comment

Comments have been disabled for this content.