Archive for June, 2015

Translating SQL to LINQ can prove difficult for new and experienced C# developers. This post contains common SQL queries written in LINQ. I hope it’ll serve as a reference when writing LINQ queries. I’ll use a MS SQL database and Entity Framework for my examples. However, these examples can be extracted to other ORMs and databases. Also, consider reading why LINQ beats SQL to learn how to think in LINQ terms rather than translating SQL to LINQ.

Data model

We’ll use a simple data model that contains books and authors for our examples.

Books authors and articles data model

Entity Framework data context

SELECT

See the data model and Entity Framework data context to understand the setup for the following examples.

*

TOP

single column

multiple columns

Where

See the data model and Entity Framework data context to understand the setup for the following examples.

single condition

AND

OR

IN

BETWEEN

Inner join

See the data model and Entity Framework data context to understand the setup for the following examples.

LEFT/RIGHT OUTER JOIN

See the data model and Entity Framework data context to understand the setup for the following examples.

LEFT

RIGHT

FULL OUTER JOIN

See the data model and Entity Framework data context to understand the setup for the following examples.

CROSS JOIN

See the data model and Entity Framework data context to understand the setup for the following examples.

GROUP BY

See the data model and Entity Framework data context to understand the setup for the following examples.

single column

multiple columns

HAVING

See the data model and Entity Framework data context to understand the setup for the following examples.

DISTINCT

See the data model and Entity Framework data context to understand the setup for the following examples.

UNION

See the data model and Entity Framework data context to understand the setup for the following examples.

UNION ALL

UNION

ORDER BY

See the data model and Entity Framework data context to understand the setup for the following examples.

single column

DESC