entity framework - load method


We use Load() method to explicitly load related data. Actually, the Entity Framework returns the data we have specified in the query. But it is possible to get the related data using the same query. For example, when we have written a query for retrieving customers, we can also get the sales order details without writing an another query. This is known as deferred loading or lazy loading. By default, the Entity Framework performs lazy loading.

Consider the following query.
using (var context = new SalesOrderManagementEntities())
{
 //1. Query all the customers using LINQ to Entities query using c#.
	var Customers = from c in context.Customer
         			select c;
	foreach (var Customer in Customers)
	{
    	Customer.Order.Load();
    	Console.WriteLine(String.Format("{0} {1} {2}",
        Customer.Name, Customer.Address, Customer.Order.Count()));
	}
	Console.WriteLine();
	Console.ReadLine();

The output of the above query is:
linq query output
In the above query, I have called Load() method. When Load is called, ObjectServices will execute a query to retrieve all of the orders of a particular customer.

Note that by default, for the models created in VS2008, lazy loading will not be enabled. So, when lazy loading is disabled, we need to explicitly call Load() method to load entity collections.

If models are created in VS2010, by default lazy loading is enabled, so, the Entity Framework retrieves all the related data using a single query without explicitly calling the Load() method.
using (var context = new SalesOrderManagementEntities())
{
 //1. Query all the customers using LINQ to Entities query using c#.
	var Customers = from c in context.Customer
         			select c;
	foreach (var Customer in Customers)
	{
    	Console.WriteLine(String.Format("{0} {1} {2}",
        Customer.Name, Customer.Address, Customer.Order.Count()));
	}
	Console.WriteLine();
	Console.ReadLine();

Performance issue with Lazy loading in Entity Framework

Whether we use lazy loading default feature or call Load() method to explicitly load related data, performance will be hit. In the above code, a new query will be executed to count number of orders for each customer which results in an addition trip to the database for each customer. If the database contains 10 customers, there will be 20 additional round trips to count number of orders. This is not efficient, Load() can be used to filter orders only for particular customers and number of round trips to the database can be reduced.