Database Reference
In-Depth Information
How It Works
Entity Framework does not directly support the notion of lazy loading of individual entity properties. To get the effect
of lazy loading expensive properties, we exploit Entity Framework's support for lazy loading of associated entities.
We created a new entity type to hold the expensive full image property and created a one-to-one association between
our
Photograph
entity type and the new
PhotographFullImage
entity type. We added a referential constraint on the
conceptual layer that, much like a database referential constraint, tells Entity Framework that a
PhotographFullImage
can't exist without a Photograph.
Due to the referential constraint, there are a couple of things to note about our model. If we have a newly created
PhotographFullImage
, an instance of
Photograph
must exist in the object context or the data source prior to calling
SaveChanges()
. Also, if we delete a photograph, the associated
PhotographFullImage
is also deleted. This is just like
cascading deletes in database referential constraints.
The code in Listing 2-15 demonstrates inserting and retrieving from our model.
Listing 2-15.
Inserting into and Lazy Loading Expensive Fields
byte[] thumbBits = new byte[100];
byte[] fullBits = new byte[2000];
using (var context = new EF6RecipesContext())
{
var photo = new Photograph { Title = "My Dog",
ThumbnailBits = thumbBits };
var fullImage = new PhotographFullImage { HighResolutionBits = fullBits };
photo.PhotographFullImage = fullImage;
context.Photographs.Add(photo);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach (var photo in context.Photographs)
{
Console.WriteLine("Photo: {0}, ThumbnailSize {1} bytes",
photo.Title, photo.ThumbnailBits.Length);
// explicitly load the "expensive" entity,
PhotographFullImagecontext.Entry(photo).Reference(p => p.PhotographFullImage).Load();
Console.WriteLine("Full Image Size: {0} bytes",
photo.PhotographFullImage.HighResolutionBits.Length);
}
}
The output from Listing 2-15 is as follows:
Photo: My Dog, Thumbnail Size: 100 bytes
Full Image Size: 2000 bytes
The code in Listing 2-15 creates and initializes instances of the
Photograph
and
PhotographFullImage
entities,
adds them to the object context, and calls
SaveChanges()
.