Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 default eager loading

I'm using Entity Framework 4.1 code first approach.

I want to make eager loading as my the dafault configuration, and by that avoid using the Include extension method in each fetching query.

I did as recomended in MSDN, changing the simple lazy property at the DbContext constructor:

public class EMarketContext : DbContext
{
    public EMarketContext()
    {
        // Change the default lazy loading to eager loading
        this.Configuration.LazyLoadingEnabled = false; 
    }
}

unfortunately, this approach is not working. I have to use the Include method to perform eager loading in each query. Any ideas why? Thanks in advance.

like image 693
Sean Avatar asked May 18 '11 08:05

Sean


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.

Which loading is setted by default in EF core?

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. For example: If the User entity has a foreign key in the Post entity.

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.

Is eager loading better than lazy loading?

Lazy Loading vs. Eager Loading. Eager loading generates all web page content as soon as possible, while lazy loading delays the display of non-essential content. Lazy loading is a great option for large page files with more content.


1 Answers

There is no default configuration for eager loading. You must always define Include or create some reusable method which will wrap adding include. For example you can place similar method to your context:

public IQueryable<MyEntity> GetMyEntities()
{
    return this.MyEntities.Include(e => e.SomeOtherEntities);
}
like image 122
Ladislav Mrnka Avatar answered Sep 28 '22 09:09

Ladislav Mrnka