Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First forced eager loading

I'm using EF 5 with Code First. I have a class that I want to always eager load some properties. I removed the virtual keyword but it's not eager loading:

public class Person
{
   public ICollection<Email> Emails { get; set; } 
   public Profile Profile {get;set;}
}

So by turning off lazy loading, it won't auto eager load right? If so, how do I archive that without using Include()?

Thanks!

like image 447
Calvin Avatar asked Aug 22 '12 00:08

Calvin


People also ask

How do I set eager loading in Entity Framework?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog. Include is an extension method in the System.

What is eager loading in EF core?

Eager loading means that the related data is loaded from the database as part of the initial query. Explicit loading means that the related data is explicitly loaded from the database at a later time.

What is lazy loading and eager loading in EF?

Lazy loading in Entity Framework is the default phenomenon that happens for loading and accessing the related entities. However, eager loading is referred to the practice of force-loading all these relations.


1 Answers

No, turning off lazy loading by removing the virtual keyword will not automatically enable eager loading. You have to Include the related Entity or Collection like so:

var personWithProfile = ctx.People.Include(x => x.Profile).First();
var personWithProfileAndEmails = ctx.People.
                                           .Include(x => x.Profile)
                                           .Include(x => x.Emails)
                                           .First();

This is a great read from the ADO.NET team blog: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

like image 94
Paul Avatar answered Oct 11 '22 04:10

Paul