实体框架: 如何禁用特定查询的延迟加载?

有没有什么方法可以在实体框架6上禁用特定查询的延迟加载?我想定期使用它,但有时我想禁用它。我使用虚拟属性来延迟加载它们。

100806 次浏览

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;

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

set the following code before the query you want to execute

context.Configuration.LazyLoadingEnabled = false;

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

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

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

Per this answer.

Another approcah for another EF Version (Entity Framework 5)

//Note: ContextOptions instead of ChangeTracker or Configuration
context.ContextOptions.LazyLoadingEnabled = false;

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

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