Databases Reference
In-Depth Information
Lazy and Eager Loading
By default in version 4 of Entity Framework, a newly created entity model has the Lazy
Loading option enabled. This allows you to traverse the navigation properties and query-
related entities without actually writing any queries at all.
var query = from p in context.Products
select p;
foreach (Product p in query)
Console.WriteLine(p.ProductName + “ “ + p.Supplier.CompanyName);
In the preceding example, there is only one explicit query, which returns all products.
However, when enumerating the
Product
objects it returns, the code also prints out the
name of the Supplier for each product. The simple act of referencing the
Supplier
prop-
erty of a
Product
instance causes the related Supplier entity to be loaded from the data-
base by the
ObjectContext
.
Code that takes advantage of lazy loading is very clean and works great when loading of
related entities is infrequent. However, a separate query is sent to the database engine
every time the Supplier property is referenced. Even though the individual queries can be
small and return little data, in a loop, it might be faster to retrieve all Suppliers along with
their Products in a single query. This is called
eager loading
. Entity Framework allows you
to do it by calling the
Include
method and specifying the name of the navigation prop-
erty that needs to be eager-loaded.
var query = from p in context.Products
.Include(“Supplier”)
select p;
foreach (Product p in query)
Console.WriteLine(p.ProductName + “ “ + p.Supplier.CompanyName);
This version of the code only executes a single database query at the beginning of the
foreach loop. The query retrieves both Product and their associated Supplier entities from
the database. No additional requests are sent to the database when the Supplier's company
name is printed out in the loop.
Projections
When a query returns entities, it needs to retrieve values of all of its properties from the
database. It is an equivalent of
SELECT *
SQL statement. When you are only interested
in a particular set of columns, you can significantly reduce the amount of data returned
and improve performance with the help of projections, or in common terms, by “select-
ing” only those columns you are interested in. The following code sample only needs
the
CompanyName
and
City
values of the Supplier entity, so instead of returning an
entire entity, it returns instances of an anonymous type that includes just the required
properties.