延迟加载 vs 急切加载 [英] Lazy Loading vs Eager Loading

查看:39
本文介绍了延迟加载 vs 急切加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么情况下,预先加载比延迟加载更有利?

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,我一直有一个问题,为什么 Microsoft 在这种情况下使用 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

何时使用预先加载

  1. 在一对多关系的一侧"中,您肯定会在任何地方与主要实体一起使用.比如文章的用户属性.产品的类别属性.
  2. 通常,当关系不是太多时,急切加载将是减少服务器上进一步查询的好习惯.

何时使用延迟加载

  1. 几乎在一对多关系的每个集合方"上.像用户的文章或类别的产品
  2. 您清楚地知道您不会立即需要房产.

注意:如 Transcendent 所说,延迟加载可能存在处理问题.

Note: like Transcendent said there may be disposal problem with lazy loading.

这篇关于延迟加载 vs 急切加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆