98

Is there any way to disable lazy loading for specific query on Entity Framework 6? I want to use it regularly, but sometimes I want to disable it. I'm using virtual properties to lazy load them.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Marco Alves
  • 2,776
  • 3
  • 23
  • 33
  • 22
    set context.Configuration.LazyLoadingEnabled = false; before the query you want to run – Karthik Ganesan Jun 03 '14 at 19:06
  • 5
    You could just set the value `this.Configuration.LazyLoadingEnabled = false;`, then set it again `this.Configuration.LazyLoadingEnabled = true;`? Also, you can read this http://msdn.microsoft.com/en-us/data/jj574232.aspx – user1477388 Jun 03 '14 at 19:07
  • 1
    thank you @KarthikGanesan. It worked as expected. – Marco Alves Jun 03 '14 at 20:40
  • @KarthikGanesan Can you put your comment as an answer ? It's working really well :) – Sampath Jun 06 '16 at 08:13
  • 1
    Added the comment as answer @Sampath – Karthik Ganesan Jun 06 '16 at 21:59
  • This is a strange question. A query never executes lazy loading. Lazy loading is all about queries that EF itself triggers when navigation properties are addressed. Therefore it's useless to disable lazy loading for the duration of one query. The question amounts to nothing but: how to disable lazy loading, period. – Gert Arnold Aug 17 '22 at 09:30

9 Answers9

88

set the following code before the query you want to execute

context.Configuration.LazyLoadingEnabled = false;
Karthik Ganesan
  • 4,142
  • 2
  • 26
  • 42
42

You can disable Lazy loading for a specific query as follows :

public static Cursos GetDatosCursoById(int cursoId)
{
    using (var bd = new AcademyEntities())
    {
        try
        {
            bd.Configuration.ProxyCreationEnabled = false;
            return bd.Cursos.FirstOrDefault(c => c.cursoId == cursoId);
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}
William Ballesteros
  • 1,001
  • 9
  • 10
28

I might be missing something here, but rather than changing the configuration each time, might another approach be to use .Include() on only those queries where you want to eager load?

Suppose we have a Product class which has a navigation property to a Colour class, you might load the Colour for a Product like this -

var product = _context.Products
    .Where(p => p.Name == "Thingy")
        .Include(x => x.Colours)
        .ToList();
Parrybird
  • 800
  • 11
  • 18
  • 1
    For me this is the best Answer here! – Ian Feb 21 '17 at 10:47
  • 1
    This falls short if you only want to eager load "products", without any includes. – Mackan Feb 01 '18 at 08:37
  • So you'd want to get 'Products' without any of their related objects, or 'Products with all their related objects?' – Parrybird Feb 01 '18 at 09:17
  • 2
    Much more useful answer. This controls the specific sub-ordinate tables that are loaded at the point where the query is being constructed. For any real world problem this has to be the way to go. – Richard Petheram Jul 02 '18 at 07:18
  • 6
    It is useful in a different way... if you do it this way one could still get lazy loading for another collection from 'Products'. Actually disabling lazy loading is more effective to guarantee that all data needed is fetched in advance and avoids creating hidden performance bottlenecks. – Doug Oct 15 '18 at 17:27
  • What will happen if I haven't turned off the lazyloading and use include? Can any one tell me how it will behave? – Sumesh Es Jul 24 '20 at 07:10
23

In EF Core: context.ChangeTracker.LazyLoadingEnabled = false;

Per this answer.

Matt Jenkins
  • 2,824
  • 1
  • 30
  • 34
16

Go to your diagram properties and find a property designated to lazy loading and disable it.

If you are using code first then go to your config area and disable it from there with:

this.Configuration.LazyLoadingEnabled = false;
ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
Juan
  • 1,352
  • 13
  • 20
  • 7
    A lot of people are visiting this question and I want to say, people DONT WRITE QUERIES WITH OUT TAKING A LOOK TO THE EXECUTION PLAN. Always know what your code send to the database or you will have performance problems. You can use linq pad or other tools to view the real query and check. – Juan Jan 24 '17 at 19:00
5

Another approcah for another EF Version (Entity Framework 5)

//Note: ContextOptions instead of ChangeTracker or Configuration
context.ContextOptions.LazyLoadingEnabled = false; 
fubo
  • 44,811
  • 17
  • 103
  • 137
2

Suppose you have this:

IOrderedQueryable<Private.Database.DailyItem> items;
using (var context = new Private.Database.PrivateDb())
{
    context.Configuration.LazyLoadingEnabled = false;
    items = context.DailyItem.OrderBy(c => c.sortOrder).OrderByDescending(c => c.isFavorite);
}

You'd still get lazy loading, despite the explicit setting of not to. The fix is easy, change it to this:

List<Private.Database.DailyItem> items;
using (var context = new Private.Database.PrivateDb())
{
    // context.Configuration.LazyLoadingEnabled = false;
    items = context.DailyItem.OrderBy(c => c.sortOrder).OrderByDescending(c => c.isFavorite).ToList();
}
Stronghold
  • 130
  • 1
  • 7
2

For EF Core to make it simple with a method you can use this helper:

public static AppDbContext DisableLazyLoading(this AppDbContext dbcontext)
{
     dbcontext.ChangeTracker.LazyLoadingEnabled = false;

     return dbcontext;

}

Using

 return dbcontext.DisableLazyLoading().Branches.Find(course.BranchId);
  • See my comment above. It's not really useful to disable lazy loading only to execute a query. This method strongly suggests that that is exactly what happens (because it's fluent, it looks like `AsNoTracking`, which *does* change behavior for one query). In reality, it just executes the query exactly as it would with LL enabled, but it turns LL off on the context for the rest of its lifetime. The way it can be used is deceptive. – Gert Arnold Aug 17 '22 at 10:11
0

i just do this in every class that need disable lazy loading and in every class just call the db without lazyloading everything work fine

    private DataContext db;

    public TheClass ()
    {
        db = new DataContext(ConString);
        db.Configuration.LazyLoadingEnabled = false;
    } ​