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.
91
votes
7 Answers
78
votes
41
votes
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;
}
}
}
23
votes
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();
15
votes
15
votes
3
votes
2
votes
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();
}
this.Configuration.LazyLoadingEnabled = false;
, then set it againthis.Configuration.LazyLoadingEnabled = true;
? Also, you can read this msdn.microsoft.com/en-us/data/jj574232.aspx – user1477388