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

后端 未结 7 2172
夕颜
夕颜 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条回答
  •  旧时难觅i
    2020-11-28 09:49

    Suppose you have this:

    IOrderedQueryable 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 items;
    using (var context = new Private.Database.PrivateDb())
    {
        // context.Configuration.LazyLoadingEnabled = false;
        items = context.DailyItem.OrderBy(c => c.sortOrder).OrderByDescending(c => c.isFavorite).ToList();
    }
    

提交回复
热议问题