EF中懒加载的机制和作用是什么?

  1. 开启了懒加载为什么还是会载入子集元素

  2. 没有关闭懒加载

clipboard.png
对字段启用 virtual 关键字
clipboard.png
返回结果
clipboard.png

  1. 比如一个文件夹下有5个子文件夹, 我按照父文件夹ID 获取子文件夹理应最多对数据库请求一次
    可是结果是对数据库做了很多重复的请求.

clipboard.png

我想要知道的是 ICollection<>, IList<>, IEnumerable<> 会对懒加载产生什么影响,
另外我想知道 Where().ToList() 和 .ToList().Where() 会对懒加载产生什么影响.
懒加载是不是 加载 db.File.Where() 的时候 不加载其中的 ICollection<> 等到 .子文件夹 的时候才会加载

阅读 7.4k
1 个回答

https://msdn.microsoft.com/en-us/data/jj574232.aspx

Turn off lazy loading for all entities


Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property. For example:

public class BloggingContext : DbContext 
{ 
    public BloggingContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进