tags:

views:

38

answers:

2

Hi -I am getting an IQueryable from my database and then I am getting another IQueryable from that first one -that is, I am filtering the first one. My question is -does this affect performance? How many times will the code call the database? Thank you.

Code:

DataContext _dc = new DataContext();

IQueryable offers =
(from o in _dc.Offers
select o);

IQueryable filtered =
(from o in offers
select new { ... } );

return View(filtered);
+2  A: 

The code you have given will never call the database since you're never using the results of the query in any code.

IQueryable collections aren't filled until you iterate through them...and you're not iterating through anything in that code sample (ah, the beauty of lazy initialization).

That also means that each of those statements will be executed as its own query against the database which results in no performance cost over doing two completely independent queries.

Justin Niessner
Thank you for your note. Just added the last line of code -I will be returning the "filtered" IQueryable.
Bruno Ligutti
@Bruno - That still won't cause the query to execute. The query (which will be a single query) won't execute until the results of the method call are iterated in your View.
Justin Niessner
A: 

SO is not a replacement for developer tools. There are many good free tools able to tell you exactly what this code translates into and how it works. Use Reflector on this method and look at what code is generated and reason for yourself what is going on from there.

James Dunne
Third sentence was enough James. The rest shows you're having a bad day pal.
Bruno Ligutti
Yeah, I pseudo-regretted posting that afterwards. I'll edit it out.
James Dunne
Note that it wasn't meant as a personal attack or in a condescending tone. I can see it's easy to read it that way, though. I do apologize; I meant no offence. It's just that it's been a recurring pattern that most of the problems seen on SO stem from the lack of drive on the questioner's end to dig deep and use the tools available.
James Dunne
Hi James thank you. I was not aware of that tool, I followed your advise and it really helped me a lot. I will definitively use it before coming to SO next time. Thank you again.
Bruno Ligutti