Entity Framework: how to disable lazy loading for a specific request?

Is there a way to disable lazy loading for a specific request in Entity Framework 6? I want to use it regularly, but sometimes I want to disable it. I use virtual properties to load them lazily.

+64
c # entity-framework lazy-loading
Jun 03 '14 at 19:03
source share
5 answers

set the following code before the query you want to execute

context.Configuration.LazyLoadingEnabled = false; 
+55
Jun 06 '16 at 21:58
source share

You can disable Lazy loading for a specific request 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; } } } 
+38
Aug 14 '15 at 14:13
source share

Maybe something is missing me, but instead of changing the configuration every time, can a different approach use .Include() only in those queries where you want to load?

Suppose we have a Product class that has a navigation property for the Colour class, you can load the Colour for the Product like this, -

 var product = _context.Products .Where(p => p.Name == "Thingy") .Include(x => x.Colours) .ToList(); 
+16
Jan 17 '17 at 10:11
source share

Go to chart properties and find the property designed for lazy loading and disable it.

If you use the code first, go to your configuration area and disconnect it from there:

 this.Configuration.LazyLoadingEnabled = false; 
+15
Mar 17 '15 at 13:58
source share

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 will still get a lazy load, despite explicitly setting not to do this. Easy to fix, replace it as follows:

 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(); } 
0
Dec 23 '18 at 2:34
source share



All Articles