Home >Database >Mysql Tutorial >How to Perform Inner Joins in LINQ to SQL Using the ON Clause?

How to Perform Inner Joins in LINQ to SQL Using the ON Clause?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 00:21:08990browse

How to Perform Inner Joins in LINQ to SQL Using the ON Clause?

Inner joins in LINQ to SQL are a mechanism that combines rows from two tables based on a common key, allowing data from both tables to be retrieved simultaneously. The syntax for inner join using ON clause in C# is as follows:

<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, the from clause specifies the first table t1 to be joined, and the join clause specifies the second table t2 to be joined. The on clause specifies row join conditions that must be met. In this case, the condition is that t1's field field must equal t2's field field.

The

select clause specifies the fields included in the result table. In this example, the t1 field for field2 and the t2 field for field3 will be included.

For example, suppose you have two tables: Dealer and DealerContact. The Dealer table contains information about resellers, and the DealerContact table contains information about reseller contacts. You can use an inner join to retrieve information from both tables based on DealerID fields (fields common to both tables).

The following code shows how to write this query in LINQ to SQL:

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

This query will return a collection of DealerContact objects, each containing the dealer's contact information.

The above is the detailed content of How to Perform Inner Joins in LINQ to SQL Using the 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