Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does calling Select() or GroupBy() in Linq to entities trigger querying 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?

like image 862
user169867 Avatar asked Jun 22 '10 19:06

user169867


People also ask

How does Select work in LINQ?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.

Which entities can LINQ use to perform queries?

LINQ to Entities queries are comprised of LINQ standard query operators (such as Select, Where, and GroupBy) and expressions (x > 10, Contact. LastName, and so on). LINQ operators are not defined by a class, but rather are methods on a class. In LINQ, expressions can contain anything allowed by types within the System.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

How LINQ query execute?

LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results.


1 Answers

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.

like image 144
Julien Lebosquain Avatar answered Sep 17 '22 19:09

Julien Lebosquain