Database Reference
In-Depth Information
How It Works
We start by using the Include() method to eagerly load the Project entity together with its related Manager for the
first Project from the data store.
After the query, we check whether the manager instance is loaded by obtaining a reference to the related
Manager entity using the Reference() method and checking the value of the IsLoaded property. Because this is an
entity reference (reference to a single parent entity), the IsLoaded property is available on the Reference property of
the DbEntityEntry type that is returned for calling the Entry() method. As we loaded both Projects and Manager, the
IsLoaded property returns true .
Next we check whether the Contractor entity collection is loaded. It is not loaded because we didn't eagerly load
it with the Include() method, nor did we load it directly (yet) with the Load() method. Once we fetch it with the
Load() method, the IsLoaded property for it is set to true .
When lazy loading is enabled on the context object, which is the default behavior, the IsLoaded property is set
to true when the entity or entity collection is referenced. Lazy loading causes Entity Framework to load the entity
or entity collection automatically when referenced. Explicit loading is similar to lazy loading, but is not automatic.
Instead, the developer must explicitly load the related entity with the Load() method, giving the developer complete
control over if and when related entities are loaded.
The exact meaning of IsLoaded can be a little more confusing than it seems it should be. IsLoaded is set by the
results of a query by calling the Load() method, or implicitly by the span of relationship keys. When you query for
an entity, there is an implicit query for the key of the related entity. If the result of this implicit query is a null key
value, then IsLoaded is set to true , indicating that there is no related entity in the database. This is the same value for
IsLoaded that we would expect if we did an explicit load on the relationship and found no related entity.
5-12. Loading Related Entities Explicitly
Problem
You want to load related entities directly, without relying on the default lazy loading behavior of Entity Framework.
Solution
Let's say that you have a model like the one in Figure 5-27 .
Figure 5-27. A model for doctors, their patients, and appointments
 
Search WWH ::




Custom Search