Using Linq - Prevent Lazy Loading in certain cases

S

sqlguru

You have two entities: Products and Orders.
The Products entity has a Orders property.

Linq automatically enabled lazy-loading but in certain cases, I would
want the Products entity to automatically load the Orders property as
well so that it won't hit the database if I'm iterating over the
orders.

Is there an automatic way?

An alternative would be to get the Products and build a list of
product IDs. Then get a list of Orders for that Product IDs. Then
iterate over the products list and assign the orders from the order
list to the order property.
 
M

Martin Honnen

You have two entities: Products and Orders.
The Products entity has a Orders property.

Linq automatically enabled lazy-loading but in certain cases, I would
want the Products entity to automatically load the Orders property as
well so that it won't hit the database if I'm iterating over the
orders.

Is there an automatic way?

Are you talking about LINQ to SQL? Or LINQ to Entities?
For LINQ to XML there is a property DeferredLoadingEnabled you can set
to false on the DataContext you have:
http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.deferredloadingenabled.aspx
Then there are LoadOptions you can set:
http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx
 
S

sqlguru

I'm talking about Linq to SQL.

If I set the DeferredLoadingEnabled to false, which method would it
use:
1) Would it get the Products and then get the Orders for each Product?
(Generates SQL query to get Products, Iterates through products, SQL
query to get orders for each product)
2) Would it get the Products, generate a list of product IDs, get the
Orders for the product IDs, iterate through the Products list and
assign the orders?

Method 2 is faster because it only requires 2 SQL queries. Method 1 is
slower because it requires a order query to run for each product.

Also If I set the defferredloadingenabled to false, would it affect
the DBML DataContext globally OR for just that instance?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top