问题描述
有人在linq2sql中有一个简单的代码示例,该示例演示了渴望加载和延迟加载之间的区别吗?
Does anyone have a simple code example in linq2sql that demonstrates the difference between Eager Loading and Lazy Loading?
推荐答案
-
延迟加载:对于给定的实体,它的关联集合在初次加载时可能为空,但是当这些集合首次被迭代时,LINQ to SQL会触发要加载的查询这些集合在加载后即可用于将来使用,而无需其他查询:
Deferred Loading: for a given entity, it's associated collections may be empty when it is first loaded, but when these collections are first iterated, LINQ to SQL fires off a query to load these collections after it is loaded the collection is then available for future use without requiring another query:
var query = from o in db.GetTable<Order>() //db is the datacontext select o; foreach(Order o in query) { foreach(OrderDetail d in o.OrderDetails)//Deferred loading { //Do something on these collections } }
-
紧急加载:立即为所有引用的实体(例如LINQ to SQL)加载关联的馆藏,将自动为所有撤回的订单提供所有
OrderDetails
Eager Loading: immediate loading the associated Collections for all referenced entities for example LINQ to SQL will automatically brings all the
OrderDetails
for all the retreived Orders
OrderDetails
仅在被迭代时才加载,因此,如果从不迭代OrderDetatils
,则永远不会执行相应的查询.The
OrderDetails
are loaded only if it is iterated, so If theOrderDetatils
are never iterated the corresponding query is never executed.DataLoadOptions op = new DataLoadOptions(); op.LoadWith<Order>(o => o.OrderDetails); db.LoadOptions = op; var query = from o in db.GetTable<Order>() select o; foreach(Order o in query) { //Order details are eager loaded; additional queries are not needed foreach(OrderDetail d in o.OrderDetails) { //do something } }
请注意:延迟执行是LINQ功能,但是延迟加载是LINQ to SQL功能
这篇关于linq2sql中的简单Eager/Lazy加载示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!