Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Lazy Loading

I am having two object classes

public class User {     public Guid Id { get; set; }     public string Name { get; set; }      // Navigation     public ICollection<Product> Products { get; set; } }  public class Product {     public Guid Id { get; set; }      // Navigation     public User User { get; set; }     public Guid User_Id { get; set; }      public string Name { get; set; } } 

When i load a user using dataContext, i get the list of Products being null (this is ok).

If i add "virtual" keyword to Products list,

public virtual ICollection<Product> Products { get; set; } 

when i load the user, i get the Products list as well.

Why is this happening? I thought that "virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)

I think i got it all wrong

like image 446
Catalin Avatar asked Jul 13 '12 11:07

Catalin


People also ask

How do I enable lazy loading code first in Entity Framework?

Entity Framework : A Comprehensive Course Lazy loading means delaying the loading of related data, until you specifically request for it. 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.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

Does EF core use lazy loading by default?

Lazy Loading is the default behavior of LINQ that's why it is the default behavior of EF Core. With lazy loading, all related entities are not loaded along with the parent entity automatically.


1 Answers

This is wrong

"virtual" keyword is used for not loading the entities unless you explicit this (using an "Include" statement)

Lazy Loading means that entities will be automatically loaded when you first access collection or navigation property, and that will happen transparently, as though they were always loaded with parent object.

Using "include" is loading on demand, when you specify properties you want to query.

Existence of virtual keyword is related only to lazy loading. virtual keyword allows entity framework runtime create dynamic proxies for your entity classes and their properties, and by that support lazy loading. Without virtual, lazy loading will not be supported, and you get null on collection properties.

Fact is that you can use "include" in any case, but without lazy loading it is the only way to access collection and navigation properties.

like image 194
archil Avatar answered Oct 05 '22 16:10

archil