Entity Framework 4.1 default eager loading

Sean picture Sean · May 18, 2011 · Viewed 8.3k times · Source

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.

Answer

Ladislav Mrnka picture Ladislav Mrnka · May 18, 2011

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);
}