Reputation: 111
I was wondering does lazy loading just works when I use virtual or I have to explicitly set it to true, like so:
DbContext.ContextOptions.LazyLoadingEnabled = true;
Upvotes: 0
Views: 574
Reputation: 39326
The true is there are other requirements you must meet if you want to enable lazy loading and to have Entity Framework track changes in your classes as the changes occur. You can find these requirements in this link:
For either of these proxies to be created:
- A custom data class must be declared with
public
access.A custom data class must not be
sealed
(NotInheritable
in Visual Basic)A custom data class must not be
abstract
(MustInherit
in Visual Basic).A custom data class must have a
public
orprotected
constructor that does not have parameters. Use aprotected
constructor without parameters if you want theCreate
method to be used to create a proxy for the POCO entity. Calling theCreate
method does not guarantee the creation of the proxy: the POCO class must follow the other requirements that are described in this topic.The class cannot implement the
IEntityWithChangeTracker
orIEntityWithRelationships
interfaces because the proxy classes implement these interfaces.The
ProxyCreationEnabled
option must be set totrue
.For lazy loading proxies:
- Each navigation property must be declared as
public
,virtual
(Overridable
in Visual Basic), and notsealed
(NotOverridable
in Visual Basic) get accessor. The navigation property defined in the custom data class must have a corresponding navigation property in
the conceptual model.For change tracking proxies:
- Each property that is mapped to a property of an entity type in the data model must have
non-sealed
(NotOverridable
in Visual Basic),public
, andvirtual
(Overridable
in Visual Basic) get and set accessors.- A navigation property that represents the "many" end of a relationship must return a type that implements
ICollection
, whereT
is the type of the object at the other end of the relationship.- If you want the proxy type to be created along with your object, use the Create method on the
DBSet<T>
when creating a new object, instead of thenew
operator.
Upvotes: 3
Reputation: 6491
By default
DbContext.ContextOptions.LazyLoadingEnabled
is set to true so if you don't forget virtual and you don't mark class as sealed it works.
Upvotes: 0
Reputation: 101604
Entity Framework Loading Related Entities
Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. [...]
To answer your question, as long as it's enabled, yes, virtual navigation properties will be lazy-loaded.
Upvotes: 0