实体框架中使用Load方法和延迟加载的区别
我读了这个 延迟加载和 Load() 之间有什么区别 线程来了解在实体框架中使用 Load 方法和延迟加载之间的区别。但在该示例中使用延迟加载和 Load 方法具有相同的效果。您能给我一个例子来了解哪里使用延迟加载以及哪里使用 Load 方法吗?
I read this What is the difference between Lazy Loading and Load() thread to understand difference between using Load method and Lazy loading in entity framework. But in that example using lazy loading and Load method have the same effect. Can you plz give me an example to understand where to use lazy loading and where to use Load method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我们假设延迟加载已关闭,并且地址不在包含 方法以下代码将引发异常,因为地址将为空。
添加 Load 调用:
显式加载地址,因此可以防止异常。
如果延迟加载位于第一个代码块上也不会引发异常,因为 EF 将加载地址为您服务 - 无需进行任何明确的调用。
我希望这会有所帮助...
If we assume Lazy Loading is off, and the Addresses weren't in an Include method the following bit of code would raise an exception because the Addresses would be empty.
Adding the Load call:
Explicitly loads the addresses and would therefore prevent an exception.
If Lazy Loading is on the first block of code would not raise an exception either because EF will load Addresses for you - without making any explicit calls.
I hope that helps a bit...
延迟加载实际上是调用
Load
方法,即使我们也使用显式加载,因为您必须手动调用Load
方法。 EFv4+中通常所说的延迟加载应该称为透明延迟加载。这意味着您不必执行任何特殊调用,EF 将为您加载关系。EF 使用动态代理进行延迟加载。这些代理是从实体派生并在运行时创建的类型。我没有看到这些代理的代码,但我相信如果支持字段为
null
,它们实际上会在属性 getter 中调用Load
。Lazy loading is actually calling
Load
method even we also use explicit loading for that because you must callLoad
method manually. What is usually used as lazy loading in EFv4+ should be called transparent lazy loading. That means that you don't have to do any special call and EF will load relation for you.EF uses dynamic proxies for lazy loading. These proxies are types derived from entities and created at runtime. I didn't see the code of these proxies but I believe that they actually call
Load
in property getter if the backing field isnull
.