实体框架中使用Load方法和延迟加载的区别

发布于 2024-11-19 22:57:50 字数 242 浏览 3 评论 0原文

我读了这个 延迟加载和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

故事↓在人 2024-11-26 22:57:50

如果我们假设延迟加载已关闭,并且地址不在包含 方法以下代码将引发异常,因为地址将为空。

var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
     if ( contact.ID == 5 ) {
        Console.WriteLine( contact.Addresses.City );
     }
}

添加 Load 调用:

var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
     if ( contact.ID == 5 ) {
        contact.Addresses.Load()
        Console.WriteLine( contact.Addresses.City );
     }
}

显式加载地址,因此可以防止异常。

如果延迟加载位于第一个代码块上也不会引发异常,因为 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.

var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
     if ( contact.ID == 5 ) {
        Console.WriteLine( contact.Addresses.City );
     }
}

Adding the Load call:

var query = from c in context.Contacts select c;
foreach ( var contact in query ) {
     if ( contact.ID == 5 ) {
        contact.Addresses.Load()
        Console.WriteLine( contact.Addresses.City );
     }
}

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...

暖伴 2024-11-26 22:57:50

延迟加载实际上是调用 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 call Load 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 is null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文