Database Reference
In-Depth Information
Entity Framework exposes the IsLoaded property that it sets to true when it is 100% certain that all data from
the specified entity or entity collection is loaded and available in the context. The model in Figure 5-26 represents
projects, the managers for the projects, and the contractors that work on the projects. To test whether a related entity
is loaded into the context object, follow the pattern shown in Listing 5-30.
Listing 5-30. Using IsLoaded to Determine Whether an Entity or Entity Collection Is in the Context
using (var context = new EFRecipesEntities())
{
var man1 = new Manager { Name = "Jill Stevens" };
var proj = new Project { Name = "City Riverfront Park", Manager = man1 };
var con1 = new Contractor { Name = "Robert Alvert", Project = proj };
var con2 = new Contractor { Name = "Alan Jones", Project = proj };
var con3 = new Contractor { Name = "Nancy Roberts", Project = proj };
context.Projects.Add(proj);
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
var project = context.Projects.Include("Manager").First();
if (context.Entry(project).Reference(x => x.Manager).IsLoaded)
Console.WriteLine("Manager entity is loaded.");
else
Console.WriteLine("Manager entity is NOT loaded.");
if (context.Entry(project).Collection(x => x.Contractors).IsLoaded)
Console.WriteLine("Contractors are loaded.");
else
Console.WriteLine("Contractors are NOT loaded.");
Console.WriteLine("Calling project.Contractors.Load()...");
context.Entry(project).Collection(x => x.Contractors).Load();
if (context.Entry(project).Collection(x => x.Contractors).IsLoaded)
Console.WriteLine("Contractors are now loaded.");
else
Console.WriteLine("Contractors failed to load.");
}
The following is the output from the code in Listing 5-30:
Manager entity is loaded.
Contractors are NOT loaded.
Calling project.Contractors.Load()...
Contractors are now loaded.
 
Search WWH ::




Custom Search