Database Reference
In-Depth Information
In the model shown in Figure 5-23 , an Employee is associated with exactly one Department. Each Department is
associated with exactly one Company.
Given an instance of an Employee, you want to load both her department and the department's company. What
makes this problem somewhat unique is that we already have an instance of Employee, and we want to avoid going
back to the database to get another copy of the Employee just so that we can use the Include() method to obtain the
related instances of Company and Department. Perhaps in your real-world problem, Employee is a very expensive
entity to retrieve and materialize.
We could use the Load() method twice to load the related Department instance and then again to load the
related Company instance. However, this would generate two round trips to the database. To load the related
instances using just one query, we can either requery the Employee entity set using the Include() method with a
query path including the Department and the Company, or combine the Reference() and Query() methods exposed
by the Entry Class. The code in Listing 5-21 shows both approaches.
Listing 5-21. Inserting into the Model and Retrieving the Related Entities Using Two Slightly Different Approaches
using (var context = new EFRecipesEntities())
{
var company = new Company { Name = "Acme Products" };
var acc = new Department { Name = "Accounting", Company = company };
var ship = new Department { Name = "Shipping", Company = company };
var emp1 = new Employee { Name = "Jill Carpenter", Department = acc };
var emp2 = new Employee { Name = "Steven Hill", Department = ship };
context.Employees.Add(emp1);
context.Employees.Add(emp2);
context.SaveChanges();
}
// First approach
using (var context = new EFRecipesEntities())
{
// Assume we already have an employee
var jill = context.Employees.First(o => o.Name == "Jill Carpenter");
// Get Jill's Department and Company, but we also reload Employees
var results = context.Employees
.Include("Department.Company")
.First(o => o.EmployeeId == jill.EmployeeId);
Console.WriteLine("{0} works in {1} for {2}",
jill.Name, jill.Department.Name, jill.Department.Company.Name);
}
// More efficient approach, does not retrieve Employee again
using (var context = new EFRecipesEntities())
{
// Assume we already have an employee
var jill = context.Employees.Where(o => o.Name == "Jill Carpenter").First();
 
Search WWH ::




Custom Search