0
0to60
Let's say we have your basic Invoices and InvoiceItems table. If we load
this in with LINQ:
var query = from i in db.Invoices
select i;
When I then loop through my invoices, if I wanna access the lineItems for a
particular invoice, LINQ runs another query behind the scenes and goes and
gets them for me. So if I wanted to loop through my invoices and print out
the number of invoices thusly:
foreach(Invoice i in query)
WriteLine(i.someInfo, i.lineItems.count);
This means I have to go to the db each time through the loop. If I have
1000 invoices, I make that many round trips to the db, plus the original
query to get the invoices in the first place.
Similarly, if I used LINQ to just gimme the lineitems and then I wanted to
loop through them and access lineItem.Invoice, that means I have to go to
the db each time through the loop. In other words, any "aggregate" objects
don't get filled by the original LINQ query; LINQ waits until you access
them and goes and gets them in a "just in time" fashion.
Now, this is nice and convenient. It takes hardly any code to write this
stuff, and it gets what it needs when it needs to and you don't have to
concern yourself with it. But, I often work with graphs such as this that
have maybe 1000 parent objects, and each one might have 100 children (and
sometimes those children have children). If I have to loop through one of
my object graphs, it would be TONS of trips to the db and long wait times
for my users.
vIs there any way to tell LINQ to get more stuff initially?
this in with LINQ:
var query = from i in db.Invoices
select i;
When I then loop through my invoices, if I wanna access the lineItems for a
particular invoice, LINQ runs another query behind the scenes and goes and
gets them for me. So if I wanted to loop through my invoices and print out
the number of invoices thusly:
foreach(Invoice i in query)
WriteLine(i.someInfo, i.lineItems.count);
This means I have to go to the db each time through the loop. If I have
1000 invoices, I make that many round trips to the db, plus the original
query to get the invoices in the first place.
Similarly, if I used LINQ to just gimme the lineitems and then I wanted to
loop through them and access lineItem.Invoice, that means I have to go to
the db each time through the loop. In other words, any "aggregate" objects
don't get filled by the original LINQ query; LINQ waits until you access
them and goes and gets them in a "just in time" fashion.
Now, this is nice and convenient. It takes hardly any code to write this
stuff, and it gets what it needs when it needs to and you don't have to
concern yourself with it. But, I often work with graphs such as this that
have maybe 1000 parent objects, and each one might have 100 children (and
sometimes those children have children). If I have to loop through one of
my object graphs, it would be TONS of trips to the db and long wait times
for my users.
vIs there any way to tell LINQ to get more stuff initially?