2

I want to fine-tune the results in the controller action with a few parameters coming from client.

I was following this answer.

The problem is the logs variable returns no results even if all the parameters are not there (I expect it to return all the records). It works perfectly fine I do

return View(db.Logs.ToList());

But my implementation of the answer by Darren Kopp doesn't return anything at all. My code:

Category cat;
DateTime startDate;
DateTime endDate;

var logs = from log in db.Logs
           select log;

if (Enum.TryParse<Category>(viewModel.Category, out cat))
    logs = logs.Where(l => l.LogCategory == cat);

if (DateTime.TryParse(viewModel.StartDate, out startDate))
    logs = logs.Where(l => l.TimeStamp >= startDate);

return View(logs.ToList());

I am using VS 2015 & this is MVC 5. What is causing the problem?

Community
  • 1
  • 1
Vivekanand P V
  • 861
  • 3
  • 13
  • 27
  • I guess you need to cast into the list just after the filtration, as in "logs = logs.Where(l => l.LogCategory == cat).ToList();" instead of "logs = logs.Where(l => l.LogCategory == cat);" – Shilpa Soni Dec 28 '15 at 12:51
  • 1
    @ShilpaSoni: No, absolutely not. The OP only needs to call `ToList` once, at the end, which is already there... – Jon Skeet Dec 28 '15 at 12:53
  • 1
    So have you debugged into the code to see what `Enum.TryParse` and `DateTime.TryParse` are actually returning? It sounds like it shouldn't be calling `Where` at all, rather than the problem being with the `Where` call itself... – Jon Skeet Dec 28 '15 at 12:54
  • Can you check in debug what values in your variables when you chouse nothing (`cat`, `startDate`, `endDate`)? I suppose even you don't fill them they have default value that ruin you everything. – teo van kot Dec 28 '15 at 12:55
  • What is the SQL being generated? Is LogCategory defined as an int in the DB? – stephen.vakil Dec 28 '15 at 15:42
  • @JonSkeet A pleasure to see your exquisite suggestion here (for a person who actually learnt a bit of C# from your videos :-). The code is actually correct but the only strange thing is .NET's conversion of empty string to date 0001-01-01. That way, the conversion succeeded but resultant query was nonsensical. I have added string.IsNullOrEmpty() to the condition and it is working perfectly fine. Enum.TryParse works neat by the way. – Vivekanand P V Jan 03 '16 at 02:18

0 Answers0