Database Reference
In-Depth Information
How It Works
The code in Listing 5-22 uses explicit loading to retrieve a collection of related entity objects and perform filtering and
ordering on them.
Along with lazy and eager loading,
explicit loading
is the third option for loading related data. When explicitly
loading data, you are in full control. You issue commands that retrieve the data. You control if, when, and where
related data is brought into the context object.
To implement explicit loading, you start with the
Entry()
method that is exposed by the DbContext object.
Entry()
accepts an argument that represents the parent entity that you wish to query.
Entry()
provides a wealth of information
about the entity, including access to the related entity objects via the
Collection()
and
Reference()
methods.
In the example above, we start with the parent entity, Hotel, and then query related Room entities by chaining
the
Collection()
method and passing in the navigation property, Rooms, as a parameter. The associated
Query()
method from the DbCollectionEntry class generates a query to load the room objects from the underlying data store.
Finally, we eagerly load the related reservations for each room by querying the Reservations navigation property
as a parameter to the
Include()
method, applying
where
clause filters to retrieve only the collection of rooms of type
ExecutiveSuite that have at least one reservation. We then order the collection by room rate using an
OrderBy
clause.
Normally, the
Include()
method returns all related objects for a parent with no opportunity to filter or manipulate
the result set. The exception to this rule is when implementing explicit loading. As demonstrated here, we are able to
filter and sort the results from related Reservation entities.
Keep in mind that we can only apply filters against related data from an
Include()
method using this pattern.
This feature is not available when implementing lazy loading or eager loading.
5-10. Executing Aggregate Operations on Related Entities
Problem
You want to apply an aggregate operator on a related entity collection without loading the entire collection.
Additionally, you want to implement the Code-First approach for Entity Framework 6 to manage data access.
Solution
Suppose that you have a model like the one shown in Figure
5-25
.
Figure 5-25.
Orders and their associated order items