Database Reference
In-Depth Information
// Leverage the Entry, Query, and Include methods to retrieve Department and Company data
// without requerying the Employee table
context.Entry(jill).Reference(x => x.Department).Query().Include(y => y.Company).Load();
Console.WriteLine("{0} works in {1} for {2}",
jill.Name, jill.Department.Name, jill.Department.Company.Name);
}
The following is the output of the code in Listing 5-21:
Jill Carpenter works in Accounting for Acme Products
Jill Carpenter works in Accounting for Acme Products
How It Works
If we didn't already have an instance of the Employee entity, we could simply use the Include() method with a
query path Department.Company . This is essentially the approach we take in earlier queries. The disadvantage of this
approach is that it retrieves all of the columns for the Employee entity. In many cases, this might be an expensive
operation. Because we already have this object in the context, it seems wasteful to gather these columns again from
the database and transmit them across the wire.
In the second query, we use the Entry() method exposed by the DbContext object to access the Employee object
and perform operations against it. We then chain the Reference() and Query() methods from the DbReferenceEntity
class to return a query to load the related Department object from the underlying data store. Additionally, we chain
the Include() method to pull in the related Company information. As desired, this query retrieves both Department
and Company data without needlessly requerying the data store for Employees data, which has already been loaded
into the context.
5-9. Filtering and Ordering Related Entities
Problem
You have an instance of an entity and you want to load a related collection of entities applying both a filter and an
ordering.
Solution
Suppose that you have a model like the one shown in Figure 5-24 .
 
Search WWH ::




Custom Search