显式和延迟加载有什么用? [英] What is the use of explicit and lazy loading?

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

问题描述

延迟加载的代码:



code for lazy loading:

viewModel.Enrollments = viewModel.Courses.Where(x => x.CourseID == courseID).Single().Enrollments;







显式加载代码:






code for explicit loading:

var selectedCourse = viewModel.Courses.Where(x => x.CourseID == courseID).Single();




db.Entry(selectedCourse).Collection(x => x.Enrollments).Load();







foreach (Enrollment enrollment in selectedCourse.Enrollments)
                  {
                      db.Entry(enrollment).Reference(x => x.Student).Load(); //explicitly loads each Enrollment entity's related student entity
                 }

                 viewModel.Enrollments = selectedCourse.Enrollments;
           }





我尝试过:



我没有尝试任何东西。只是问这两者的区别。谢谢



What I have tried:

I havent tried anything. Just asking whats the difference of this two. Thanks

推荐答案

当您尝试在代码中访问引用数据时,延迟加载会发出更多SQL语句。渴望加载往往有一个更复杂的语句,一次加载所有数据。延迟加载的优点主要在于您不打算处理所有延迟时。例如,假设您有客户和客户订单,并且您只想查看具有特定属性的客户的客户订单,然后通过延迟加载您可以查看每个客户,如果它具有该属性,则可以访问customer.Orders和在那时订单已加载。这样,如果您不打算使用它,您就不会花时间获取所有客户订单的数据。但是,如果您知道要访问所有数据(或大部分数据),那么延迟加载就没有用了。



延迟加载对于代码响应用户输入的桌面应用程序。例如,您可能拥有客户的树状视图,当您扩展客户时,您可以加载订单。在网页上虽然你没有这种交互,但是你要一次性构建整个页面,所以对延迟加载的使用较少。
Lazy loading issues more SQL statements where you load the referenced data when you try and access it in code. Eager loading tends to have a single, more complex statement that loads all the data in one go. The advantage of lazy loading is mainly when you don't intended on processing all of it. For example let's say you have customers and customer orders and you only want to look at customer orders for customers with a certain property, then with lazy loading you can look at each customer and if it has the property you could then access customer.Orders and at that point Orders is loaded. That way you don't spend time getting data for all customer orders if you're not going to use it. However if you know you are going to access all data (or most of it) then there is no real use for lazy loading.

Lazy loading is also more helpful for desktop apps where the code is reacting to user input. For example you might have a tree view with customers and when you expand a customer you then load the orders. On a web page though you don't have that kind of interaction, you're building the whole page in one go so again there is less use for lazy loading.


有很多讨论以及谈论它们之间差异的文章。这是我发现的一个总结它们之间的区别:在实体框架中加载,延迟加载和显式加载 [ ^ ]
There's alot of discussions and articles that talks about the differences between them. Here's one I found that summarizes the difference between them: Eager Loading, Lazy Loading And Explicit Loading In Entity Framework[^]


这篇关于显式和延迟加载有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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