views:

31

answers:

3

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?

+2  A: 

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.

Julien Lebosquain
Are you sure calling GroupBy on an IEnumerable rather than an IQueryable will cause the query to be sent to the database? I thought it was only when you begin enumerating that the query is sent.
Mark Byers
A: 

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.

korchev
+1  A: 

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.

Mark Byers
Thanks for the tip, but I don't think I can see a running Log in Linq-to-entities...
You could perhaps look at this question and its answers: http://stackoverflow.com/questions/137712/sql-tracing-linq-to-entities
Mark Byers