List 1: deferred loading
Northwnd db = new Northwnd(@"northwind.mdf" /* connectionstring*/);
IQueryable
from ord in db.Orders
where ord.ShipVia == 3
select ord;
foreach(Order ord in query)
{
if(order.Freight>200)
{
SendCustomerNotification(ord.Customer);
}
ProcessOrder(ord);
}
by default, LINQ to SQL is deferred loading. i.e. load data when ever it has to. In list 1, LINQ runtime doesn't know if need to load all customers or some customers. it behaves deferred loading and as a result, for each order with freight greater than 200, access database and load its corresponding customer.
If you know what customers are needed, you can let LINQ runtime load all the customers needed once together with loading of the orders. List 2 shows that.
List 2: Immediate loading
Northwnd db = new Northwnd(@"northwind.mdf" /* connectionstring*/);
db.DeferredLoadingEnabled = false;
IQueryable
from ord in db.Orders
where ord.ShipVia == 3
select ord;
foreach(Order ord in query)
{
ProcessOrder(ord);
}
In List 2, the LINQ runtime will load all orders and their related customers once rather than one at a time.
No comments:
Post a Comment