Database Reference
In-Depth Information
// Currently, there isn't an easy way to refresh entities with the DbContext API.
// Instead, drop down into the ObjectContext and perform the following actions
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var objectSet = objectContext.CreateObjectSet<Appointment>();
objectSet.MergeOption = MergeOption.OverwriteChanges;
objectSet.Load();
Console.WriteLine("Collection loaded()'ed with MergeOption.OverwriteChanges");
Console.WriteLine("There are now {0} appointments for Dr. {1}",
doctorJoan.Appointments.Count(),
doctorJoan.Name);
}
// Demonstrating loading part of the collection then Load()'ing the rest
using (var context = new EFRecipesEntities())
{
// disable lazy loading feature as we are explicitly loading
// child entities
context.Configuration.LazyLoadingEnabled = false;
// Load the first doctor and attach just the first appointment
var doctorJoan = context.Doctors.First(o => o.Name == "Joan Meyers");
context.Entry(doctorJoan).Collection(x => x.Appointments).Query().Take(1).Load();
Console.WriteLine("Dr. {0} has {1} appointments loaded.",
doctorJoan.Name,
doctorJoan.Appointments.Count());
// When we need all of the remaining appointments, simply Load() them
context.Entry(doctorJoan).Collection(x => x.Appointments).Load();
Console.WriteLine("Dr. {0} has {1} appointments loaded.",
doctorJoan.Name,
doctorJoan.Appointments.Count());
}
The output of the code in Listing 5-31 is the following:
Dr. Joan Meyers's appointments were explicitly loaded
Dr. Joan Meyers has 2 appointment(s)
Dr. Joan Meyers was already loaded
Dr. Steven Mills was lazy loaded
Dr. Joan Meyers was already loaded
There are 2 appointments for Dr. Joan Meyers
Collection clear()'ed
There are now 0 appointments for Dr. Joan Meyers
Collection loaded()'ed
There are now 0 appointments for Dr. Joan Meyers
Collection loaded()'ed with MergeOption.OverwriteChanges
There are now 2 appointments for Dr. Joan Meyers
Dr. Joan Meyers has 2 appointments loaded
Dr. Joan Meyers has 2 appointments loaded
Search WWH ::




Custom Search