Member-only story
A hands-on article with example
How To Convert a SQL Query Into C# LINQ
In this article, I’ll show you what the basic steps are for converting a SQL query into LINQ. You’ll learn the basic steps needed while we convert an example query.
In this article, it's assumed that you have a basic understanding of SQL, and know how to write C# code.
Introduction
Structured Query Language (SQL) is a powerful language for working with relational databases. It is widely used to retrieve and manipulate data from a variety of databases. However, when it comes to working with data in C# code, Language Integrated Query (LINQ) is a popular alternative to SQL. In this article, we will show how to manually convert a SQL query into LINQ, step-by-step.
Example SQL Query
Let’s begin with an example SQL query that includes a join, a couple of where conditions, and ordering. Here is the query:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
WHERE Orders.ShippedDate IS NULL AND Orders.Freight > 100
ORDER BY Orders.OrderDate DESC
Step-by-Step Conversion to LINQ
Let’s begin with the overall steps that you need to perform when converting your SQL into LINQ.
Step 1: Analyse The SQL Query
When you have selected the query you need to convert into LINQ, it makes sense that you at least understand how the SQL is put together.
I often do this — with SQL not written by me — by walking through the query from top to bottom and marking anything that’s unclear. I tend to use Visual Studio Code and SQL comments for this:
-- just writing a comment above the lines that are unclear
Then I’d look up / Google any functions or constructions that aren’t clear to me, so I can get a grasp of the functionality.
When I know what the query does functionally, I write down the query’s functionality in my own words. For example, for our example query the explanation would be: