Database Reference
In-Depth Information
var jobsite = new JobSite { JobSiteName = "City Arena",
Address = "123 Main", City = "Anytown",
State = "TX", ZIPCode = "76082",
Phone = phone };
jobsite.Foremen.Add(foreman1);
jobsite.Foremen.Add(foreman2);
var plumber = new Plumber { Name = "Jill Nichols",
Email = " JNichols@plumbers.com " ,
JobSite = jobsite };
context.Tradesmen.Add(plumber);
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
var plumber = context.Tradesmen.OfType<Plumber>()
.Include("JobSite.Phone")
.Include("JobSite.Foremen").First();
Console.WriteLine("Plumber's Name: {0} ({1})", plumber.Name, plumber.Email);
Console.WriteLine("Job Site: {0}", plumber.JobSite.JobSiteName);
Console.WriteLine("Job Site Phone: {0}", plumber.JobSite.Phone.Number);
Console.WriteLine("Job Site Foremen:");
foreach (var boss in plumber.JobSite.Foremen)
{
Console.WriteLine("\t{0}", boss.Name);
}
}
The following output is produced by code in Listing 5-13:
Plumber's Name: Jill Nichols ( JNichols@plumbers.com )
Job Site: City Arena
Job Site Phone: 817 867-5309
Job Site Foremen:
Carl Ramsey
Nancy Ortega
How It Works
Our query starts by selecting instances of the derived type Plumber. To fetch them, we use the OfType<Plumber>()
method. The OfType<>() method selects instances of the given subtype from the entity set.
From Plumber, we want to load the related JobSite and the Phone for the JobSite. Notice that the JobSite entity
does not have a Phone navigation property, but JobSite derives from Location, which does have a Phone navigation
property. Because Phone is a property of the base entity, it's also available on the derived entity. That's the beauty of
inheritance. This makes the query path simply: JobSite.Phone .
Then we again use the Include() method with a query path that references the Foreman entities from the
JobSite entity. Here we have a one-to-many association, JobSite and Foreman. Notice that the wizard pluralized the
navigation property (from Foreman to Foremen).
Finally, we use the First() method to select just the first Plumber instance. Doing so returns a type of Plumber,
as opposed to a collection of Plumber objects.
 
 
Search WWH ::




Custom Search