Saturday 30 March 2019

C# LINQ Joins With SQL

There are Different Types of SQL Joins which are used to query data from more than one database tables. In this article, you will learn about how to write SQL joins queries in LINQ using C#. LINQ has a JOIN query operator that gives you SQL JOIN like behavior and syntax.

Types of LINQ Joins

Venn diagram for LINQ Joins

The JOIN query operator compares the specified properties/keys of two collections for equality by using the EQUALS keyword. By default, all join queries written by the JOIN keyword are treated as equijoins. Let's understand the LINQ Joins using Venn diagram.

LINQ Queries using LINQ PAD

I am a big fan of LINQ Pad since it allows us to run LINQ to SQL and LINQ to Entity Framework query and gives the query output. Whenever I need to write LINQ to SQL and LINQ to Entity Framework query then, I prefer to write and run the query on LINQ PAD. By using LINQ PAD, you can test and run your desired LINQ query and avoid the head-ache for testing LINQ query within Visual Studio. You can download the LINQ Pad script used in this article by using a download link at the top.
In this article, I am using LINQ PAD for query data from the database. It is simple and useful. For more help about LINQ PAD refer the link. Suppose, we have three tables and data in these three tables is shown in the given figure.

INNER JOIN

Inner join returns only those records or rows that match or exists in both the tables.

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. orderby od.OrderID
  4. select new {
  5. od.OrderID,
  6. pd.ProductID,
  7. pd.Name,
  8. pd.UnitPrice,
  9. od.Quantity,
  10. od.Price,
  11. }).ToList();

LINQ Pad Query

INNER JOIN Among More than Two Tables

Like SQL, we can also apply to join on multiple tables based on conditions as shown below.

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. join ct in dataContext.tblCustomers on od.CustomerID equals ct.CustID
  4. orderby od.OrderID
  5. select new {
  6. od.OrderID,
  7. pd.ProductID,
  8. pd.Name,
  9. pd.UnitPrice,
  10. od.Quantity,
  11. od.Price,
  12. Customer=ct.Name //define anonymous type Customer
  13. }).ToList();

LINQ Pad Query

INNER JOIN On Multiple Conditions

Sometimes, we required to apply to join on multiple conditions. In this case, we need to make two anonymous types (one for the left table and one for the right table) by using new keyword then we compare both the anonymous types.

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. join ct in dataContext.tblCustomers
  4. on new {a=od.CustomerID,b=od.ContactNo} equals new {a=ct.CustID,b=ct.ContactNo}
  5. orderby od.OrderID
  6. select new {
  7. od.OrderID,
  8. pd.ProductID,
  9. pd.Name,
  10. pd.UnitPrice,
  11. od.Quantity,
  12. od.Price,
  13. Customer=ct.Name //define anonymous type Customer
  14. }).ToList();

LINQ Pad Query

NOTE

  1. Always remember, both the anonymous types should have the exact same number of properties with same name and datatype otherwise you will get the compile-time error "Type inference failed in the call to Join".
  2. Both the comparing fields should define either NULL or NOT NULL values.
  3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of a NOT NULL field to NULL data type like as above fig.

LEFT JOIN or LEFT OUTER JOIN

LEFT JOIN returns all records or rows from the left table and from right table returns only matched records. If there are no columns matching in the right table, it returns NULL values.
In LINQ to achieve LEFT JOIN behavior, it is mandatory to use "INTO" keyword and "DefaultIfEmpty()" method. We can apply LEFT JOIN in LINQ like as :

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. into t from rt in t.DefaultIfEmpty()
  4. orderby pd.ProductID
  5. select new {
  6. //To handle null values do type casting as int?(NULL int)
  7. //since OrderID is defined NOT NULL in tblOrders
  8. OrderID=(int?)rt.OrderID,
  9. pd.ProductID,
  10. pd.Name,
  11. pd.UnitPrice,
  12. //no need to check for null since it is defined NULL in database
  13. rt.Quantity,
  14. rt.Price,
  15. }).ToList();

LINQ Pad Query

CROSS JOIN

Cross join is a cartesian join means a cartesian product of both the tables. This join does not need any condition to join two tables. This join returns records or rows that are a multiplication of record number from both the tables means each row on the left table will be related to each row of a right table.
In LINQ to achieve CROSS JOIN behavior, there is no need to use Join clause and where clause. We will write the query as shown below.

C# Code

  1. var q = from c in dataContext.Customers from o in dataContext.Orders
  2. select new {
  3. c.CustomerID,
  4. c.ContactName,
  5. a.OrderID,
  6. a.OrderDate
  7. };

LINQ Pad Query

GROUP JOIN

When a join clause uses an INTO expression, then it is called a group join. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. If the right collection has no matching elements with left collection then an empty array will be produced.

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. into t orderby pd.ProductID
  4. select new{
  5. pd.ProductID,
  6. pd.Name,
  7. pd.UnitPrice,
  8. Order=t
  9. }).ToList();

LINQ Pad Query

Basically, GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.

GROUP JOIN As SubQuery

We can also use the result of a GROUP JOIN as a subquery like as:

C# Code

  1. var q=(from pd in dataContext.tblProducts
  2. join od in dataContext.tblOrders on pd.ProductID equals od.ProductID
  3. into t from rt in t
  4. where rt.Price>70000
  5. orderby pd.ProductID
  6. select new {
  7. rt.OrderID,
  8. pd.ProductID,
  9. pd.Name,
  10. pd.UnitPrice,
  11. rt.Quantity,
  12. rt.Price,
  13. }).ToList();

LINQ Pad Query

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...