Entity Framework: How to disable lazy loading for specific query?

后端 未结 7 2117
夕颜
夕颜 2020-11-28 09:22

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 propert

相关标签:
7条回答
  • 2020-11-28 09:24

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

    Per this answer.

    0 讨论(0)
  • 2020-11-28 09:24

    Another approcah for another EF Version (Entity Framework 5)

    //Note: ContextOptions instead of ChangeTracker or Configuration
    context.ContextOptions.LazyLoadingEnabled = false; 
    
    0 讨论(0)
  • 2020-11-28 09:30

    You can disable Lazy loading for 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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 09:36

    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;
    
    0 讨论(0)
  • 2020-11-28 09:43

    set the following code before the query you want to execute

    context.Configuration.LazyLoadingEnabled = false;
    
    0 讨论(0)
  • 2020-11-28 09:43

    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();
    
    0 讨论(0)
提交回复
热议问题