Dela via


LINQ to SQL Queries

You define LINQ to SQL queries by using the same syntax as you would in LINQ. The only difference is that the objects referenced in your queries are mapped to elements in a database. For more information, see Introduction to LINQ Queries.

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. The ADO provider returns query results as a DataReader. The LINQ to SQL provider translates the ADO results to an IQueryable collection of user objects.

The following illustration depicts this general flow.

Query Execution Diagram

LINQ to SQL Queries

Note

Most methods and operators on .NET Framework built-in types have direct translations to SQL. Those that LINQ cannot translate generate run-time exceptions. For more information, see SQL-CLR Type Mapping (LINQ to SQL).

The following table shows the similarities and differences between LINQ and LINQ to SQL query items.

Item

LINQ Query

LINQ to SQL Query

Return type of the local variable that holds the query (for queries that return sequences)

Generic IEnumerable

Generic IQueryable

Specifying the data source

Uses the From (Visual Basic) or from (C#) clause

Same

Filtering

Uses the Where/where clause

Same

Grouping

Uses the Group…By/groupby clause

Same

Selecting (Projecting)

Uses the Select/select clause

Same

Deferred versus immediate execution

See Introduction to LINQ Queries

Same

Implementing joins

Uses the Join/join clause

Can use the Join/join clause, but more effectively uses the AssociationAttribute attribute. For more information, see Querying Across Relationships (LINQ to SQL).

Remote versus local execution

 

For more information, see Remote vs. Local Query Execution (LINQ to SQL).

Streaming versus cached querying

Not applicable in a local memory scenario

 

See Also

Concepts

Introduction to LINQ Queries

Basic LINQ Query Operations (C#)

Type Relationships in LINQ Query Operations (C#)

Other Resources

Query Concepts in LINQ to SQL