Database Reference
In-Depth Information
The model depicted in Figure 5-27 represents doctors, their patients, and appointments. To explicitly load related
entities, follow the pattern in Listing 5-31.
Listing 5-31. Using the Load() Method
using (var context = new EFRecipesEntities())
{
// disable lazy loading feature as we are explicitly loading
// child entities
context.Configuration.LazyLoadingEnabled = false;
var doctorJoan = context.Doctors.First(o => o.Name == "Joan Meyers");
if (!context.Entry(doctorJoan).Collection(x => x.Appointments).IsLoaded)
{
context.Entry(doctorJoan).Collection(x => x.Appointments).Load();
Console.WriteLine("Dr. {0}'s appointments were explicitly loaded.",
doctorJoan.Name);
}
Console.WriteLine("Dr. {0} has {1} appointment(s).",
doctorJoan.Name,
doctorJoan.Appointments.Count());
foreach (var appointment in context.Appointments)
{
if (!context.Entry(appointment).Reference(x => x.Doctor).IsLoaded)
{
context.Entry(appointment).Reference(x => x.Doctor).Load();
Console.WriteLine("Dr. {0} was explicitly loaded.",
appointment.Doctor.Name);
}
else
Console.WriteLine("Dr. {0} was already loaded.",
appointment.Doctor.Name);
}
Console.WriteLine("There are {0} appointments for Dr. {1}",
doctorJoan.Appointments.Count(),
doctorJoan.Name);
doctorJoan.Appointments.Clear();
Console.WriteLine("Collection clear()'ed");
Console.WriteLine("There are now {0} appointments for Dr. {1}",
doctorJoan.Appointments.Count(),
doctorJoan.Name);
context.Entry(doctorJoan).Collection(x => x.Appointments).Load();
Console.WriteLine("Collection loaded()'ed");
Console.WriteLine("There are now {0} appointments for Dr. {1}",
doctorJoan.Appointments.Count().ToString(),
doctorJoan.Name);
 
Search WWH ::




Custom Search