Does anyone have a simple code example in linq2sql that demonstrates the difference between Eager Loading and Lazy Loading?
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
}
}
The OrderDetails
are loaded only if it is iterated, so If the OrderDetatils
are never iterated the corresponding query is never executed.
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
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
}
}
note that: Deferred execution is a LINQ Feature but Deferred Loading is a LINQ to SQL feature