Well guys, this problem just baffles me. I hope someone can explain to me what is going on because I think I’m losing my mind… 🙂
The situation is as follows:
In my Index method (MVC2 application), I query the entire content of a table in my database, and insert it into the ‘temp’ variable. I then narrow down the list based on what parameters have been passed to my method.
if (int.TryParse(costcenter, out tempint) && !string.IsNullOrWhiteSpace(costcenter))
{
Trace.Write("From " + temp.Count());
temp = temp.Where(x => x.tbl_CostCenters.Id == tempint);
Trace.WriteLine(" to " + temp.Count());
}
if (int.TryParse(supplier, out tempint) && !string.IsNullOrWhiteSpace(supplier))
{
temp = temp.Where(x => x.tbl_EquipmentType.tbl_Suppliers.id == tempint);
}
Trace.WriteLine(" to " + temp.Count());
These parameters are passed as string, so I convert them to ints, then use a query to filter based on the values (if any). What I noticed was, when I select a CostCenter to filter on (and nothing else, all other variables are null), no results were return. I added some tracing to check how many items should be displayed. Given the 3 Trace.Write command in there, i expected my output to be the following:
From 8989 to 65
to 65
However, what I get is:
From 8989 to 65
to 0
Which means something is going amiss in the ‘supplier’-filter. I debugged it and stepped through piece by piece, the program does the following:
- After writing the ” to 65″ string, the program jumps to the “if(…supplier…)”
- Debugging watch: tempint = 0, supplier = null
- The program skips directly to the next Trace.Writeline as the evaluation is false
- Suddenly, my temp variable contains no elements.
I’m puzzled by this because my method is not executing any command related to the temp variable, yet it gets emptied.
Also, when I comment the “supplier”-filter (the entire IF-block), the code work. The error is occuring in the “Supplier”-filter.
Anyone have an idea as to why this is occuring? Thanks in advance!
UPDATE
If I comment out only the content of the “supplier”-if-block, and keep the if-block itself, it also goes amiss. So the problem is occuring in the evaluation of the if-statement. Am I losing my mind here? 🙁
FURTHER UPDATE
Well, I fixed it by adding .ToList() to every statement so that temp is now an IEnumerable rather than an IQueryable.
I’m still puzzled as to why this is happening. Can anyone explain why it doesn’t work without converting temp to a List?
Found it out that you need to do a .ToList(), else your query keeps working by reference rather than by value.
Always do a .ToList() 🙂