Database Reference
In-Depth Information
Chapter 5
Loading Entities and Navigation
Properties
Entity Framework provides a rich modeling environment that enables the developer to work visually with entity
classes that map to database tables, views, stored procedures, and relationships. The recipes in this chapter show you
how to control the loading of related entities in your query operations.
The default behavior for Entity Framework is to load only the entities directly needed by your application. In general,
this is exactly what you want. If Entity Framework aggressively loaded all of the entities related through one or more
associations, you would likely end up loading more entities than you needed. This would increase the memory footprint
of your application as well as impact performance.
In Entity Framework, you can control when the loading of related entities occurs and optimize the number of
database queries executed. Carefully managing if and when related entities are loaded can increase application
performance and provide you more control over your data.
In this chapter, we illustrate the various options available for loading related data along with an explanation
about the benefits and drawbacks of each. Specifically, we discuss the default behavior of lazy loading and what it
really means. Then we'll look at a number of recipes illustrating the various options you have to load some or all of
the related entities in a single query. This type of loading, called eager loading , is used both to reduce the number of
round trips to the database and, more precisely, to control which related entities are loaded.
Sometimes you need to defer loading of certain related entities because they may be expensive to load or are not
used very often. For these cases, we'll cover yet another approach to loading related entities, entitled explicit loading,
and demonstrate a number of scenarios using the Load() method to control precisely when to load one or more
related entities.
Finally, we'll take a brief look at some of the asynchronous operations that are now available.
5-1. Lazy Loading Related Entities
Problem
You want to load an entity and then load related entities, only if and when they are needed by your application.
Solution
Let's say that you have a model like the one shown in Figure 5-1 .
 
Search WWH ::




Custom Search