13

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
Sean
  • 141
  • 1
  • 3

1 Answers1

26

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);
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • According to the ADO.Net developers, you're wrong. check this out: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx?CommentPosted=true#commentmessage – Sean May 18 '11 at 09:12
  • No I'm not wrong. I know this article and there is not any part which would describe "permanent `Include`" – Ladislav Mrnka May 18 '11 at 09:22
  • please look at (in the middle) : "Turn off lazy loading for all entities". – Sean May 18 '11 at 09:28
  • 8
    But it doesn't change lazy loading to eager loading. It just turns off lazy loading. Eager loading is still manual operation performed by `Include` – Ladislav Mrnka May 18 '11 at 09:33
  • @LadislavMrnka - Include will only eager load one projection. What if you need to eager load further? .Include( entity => entity.FirstCollection.Select( fc => fc.FirstProjection.Select( **this projection fails to generate a properly defined SQL statement** ))) – Travis J Jul 29 '12 at 20:34
  • I won't even dare to argue a 218K user :) – Liron Harel Aug 01 '14 at 18:23