0

The following screenshot shows how both queries return all data sets. Both in the debugger (without the Any()) and when I don't run the application in the debugger I see items in e and q.

I thought IQueryable would only run the query on operations like ToList(). Please help me to understand this.

enter image description here

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • when you expand the IQueryable object using debug mode it will execute the query attached and since your query is to return all the equipments it will return the same result as IEnumerable. Refer this: https://www.c-sharpcorner.com/UploadFile/a20beb/ienumerable-vs-iqueryable-in-linq/ – Kunal Khivensara Jul 05 '23 at 10:09
  • @KunalKhivensara And if I don't start the application in debug mode, but instead look at the result of Console.Write(q.Any()); output to the console, I also get true. Does that mean that q.Any() also performs a database call (select *)? – Love Coding Jul 05 '23 at 10:17
  • Absolutely - `Any()` will execute a query that will return TRUE if there are any records that would be returned by the underlying query, which in your case is the whole table and would hopefully be turned into a `SELECT TOP 1 NULL FROM Equipment` SQL Query or something equivalent. – D Stanley Jul 06 '23 at 00:10

1 Answers1

4

Debugger will materialize the IQueryable when you open the results view (as far as I remember it is even mentioned in the debugger, but I maybe confusing IDEs), if you will not try to view the results then it will not query the database and will not return all the items matching the query (in your case the whole Equipment table, if there are no query filters set).

I thought IQueryable would only run the query on operations like ToList()

Yes, exactly, IQueryable (as IEnumerable, but there is a caveat when casting the former to latter, then EF will need to materialize the data - see Client vs. Server Evaluation) is lazy and the actual operation will be performed only when materialization operation will happen (ToList, Any, Count etc.)

Does that mean that q.Any() also performs a database call (select *)

You are using EF Core, so no, it does not. It will perform select exists (...) or something similar. You can enable actual query logging - for example using simple logging to console.

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132