Home >Database >Mysql Tutorial >How to Perform LINQ to SQL Inner Joins with an ON Clause?

How to Perform LINQ to SQL Inner Joins with an ON Clause?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-21 00:43:09761browse

How to Perform LINQ to SQL Inner Joins with an ON Clause?

Use ON clause to perform LINQ to SQL inner join

LINQ to SQL provides a convenient way to perform complex database queries using SQL-like C# syntax. Inner joins are a common operation that allow you to combine data from multiple tables based on matching criteria.

To perform an inner join using the ON clause in LINQ to SQL, you can use the following syntax:

<code class="language-csharp">from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}</code>

In this example, t1 and t2 represent the tables to be joined, field is the column to perform the join on, and field2 and field3 are the columns to be returned in the result.

Example:

Consider the following SQL query:

<code class="language-sql">select DealerContact.*
from Dealer 
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID</code>

The equivalent LINQ to SQL query is as follows:

<code class="language-csharp">var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;</code>

In this case, the join condition is contact.DealerId equals dealer.ID, which ensures that only rows with matching dealer IDs are combined. The query returns a list of DealerContact objects.

The above is the detailed content of How to Perform LINQ to SQL Inner Joins with an ON Clause?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn