Database Reference
In-Depth Information
PreserveChanges option is, essentially, the opposite of the OverwriteChanges option.
It will update the values of any entities that have database changes, but no in-memory
changes. An entity that has been modified in memory will not be refreshed. To be precise, the
current value of an entity modified in memory will not be changed, but the original value will
be updated if it has changed on the database.
There are some restrictions on when you can use Load() . Load() cannot be called on an entity that is in the
Added, Deleted, or Detached state.
The Load() method can be helpful in improving performance by restricting how much of a collection is loaded
at any one time. For example, suppose our doctors had lots of appointments, but in many cases we needed to work
with just a few of them. In the rare case that we need the entire collection, we can simply call Load() to append the
remaining appointment instances to the context. This is demonstrated in the code snippet in Listing 5-32.
The
Listing 5-32. Code Snippet Demonstrating Partial Loading of an Entity Collection
// Demonstrating loading part of the collection then Load()'ing the rest
using (var context = new EFRecipesEntities())
{
// 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();
// note that IsLoaded returns false here since all related data has not been loaded into the context
var appointmentsLoaded = context.Entry(doctorJoan).Collection(x => x.Appointments).IsLoaded;
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 snippet in Listing 5-12b is the following:
Dr. Joan Meyers has 1 appointments loaded.
Dr. Joan Meyers has 2 appointments loaded.
5-13. Filtering an Eagerly Loaded Entity Collection
Problem
You want to filter an eagerly loaded collection. Additionally, you want to implement the Code-First approach for
Entity Framework 6 to manage data access.
 
Search WWH ::




Custom Search