问题描述
在什么情况下预加载比延迟加载更有利?
Under what situation could eager loading be more beneficial than lazy loading?
实体框架中的延迟加载是加载和访问相关实体时发生的默认现象.然而,急切加载是指强制加载所有这些关系的做法.
Lazy loading in Entity Framework is the default phenomenon that happens for loading and accessing the related entities. However, eager loading is referred to the practice of force-loading all these relations.
我问这个,因为很明显延迟加载对资源更友好,即使我们使用 ToList()
方法,我们仍然可以利用延迟加载行为.
I'm asking this, because it is obvious that lazy loading is more resource-friendly, and even if we use the ToList()
method, we can still take advantage of the lazy loading behavior.
但是,我认为延迟加载可能会增加对实际数据库的请求数量,这可能就是开发人员有时使用 Inlcude
方法强制加载所有关系的原因.
However, I thought maybe lazy loading increases the number of requests to the actual database and maybe that's why sometimes developers use the Inlcude
method to force-loading all relations.
例如,当在 MVC 5 中使用 Visual Studio 自动脚手架时,在控制器中自动创建的 Index 方法总是使用 Eager Loading,我一直有一个问题,为什么微软在这种情况下使用 Eager Loading 默认值.
For example, when using the Visual Studio auto-scaffolding in MVC 5, the Index method automatically created in the controller always uses Eager Loading, and I've always had the question of why Microsoft uses Eager Loading default in that case.
如果有人向我解释在什么情况下急切加载比延迟加载更有益,我将不胜感激,以及为什么我们要使用它,而有一些比延迟加载更资源友好的东西?
I would appreciate it if someone explains to me under what situation eager loading would be more beneficial than lazy loading, and why do we use it at all while there's something more resource-friendly as Lazy Loading?
推荐答案
我觉得这样分类关系很好
I think it is good to categorize relations like this
何时使用预加载
- 在一对多关系的一侧"中,您肯定会在主实体的任何地方使用.比如文章的用户属性.产品的类别属性.
- 通常,当关系不是太多时,预先加载将是减少服务器上进一步查询的好习惯.
何时使用延迟加载
- 几乎在一对多关系的每个集合方".喜欢用户的文章或某个类别的产品
- 您完全知道您不会立即需要房产.
注意:像超凡所说的延迟加载可能存在处理问题.
Note: like Transcendent said there may be disposal problem with lazy loading.
这篇关于延迟加载与急切加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!