I have a hard time telling what operations in linq cause a SQL command to be issued to the database.
I know calling ToList() or iterating w/ foreach will cause the query to run but do Select and GroupBy cause the code to execute on the database?
I have a hard time telling what operations in linq cause a SQL command to be issued to the database.
I know calling ToList() or iterating w/ foreach will cause the query to run but do Select and GroupBy cause the code to execute on the database?
No, they don't, if they're correctly called on the IQueryable
rather than the IEnumerable
, they are compiled as expressions and will later be translated to SQL.
You can use the intellisense tooltip to see which will be the currently called method. If the first parameter of the extension method is IEnumerable
rather than IQueryable
, you'll run into a database query.
No, calling Select() and GroupBy() will not hit the database. Only when the actual result is required (when enumerating, using ToList(), ToArray(), Count() etc) will the query get executed against the database.
No, Select
, GroupBy
and most other methods will not cause a database request. A database request will typically only be made when you do something that requires the results to be known, such as calling Count
or ToList
as you mentioned.
To help you see when database queries are made it might help to log them. Then as you step through the code you can see when the query is sent.