Home >Database >Mysql Tutorial >How Do I Perform Inner Joins in LINQ to SQL?

How Do I Perform Inner Joins in LINQ to SQL?

DDD
DDDOriginal
2025-01-21 00:31:09864browse

How Do I Perform Inner Joins in LINQ to SQL?

LINQ to SQL inner join: syntax and examples

Inner joins in LINQ to SQL combine rows from multiple tables based on matching predicates. The result set contains only rows that meet the join criteria. To perform an inner join using the ON clause, use the following syntax:

<code class="language-csharp">from t1 in table1
join t2 in table2 on t1.property equals t2.property
select new { t1.property1, t2.property2 } // 选择要包含在结果集中的字段</code>

For example, the following query returns all records in the DealerContact table that have matching DealerID values ​​in the Dealer table:

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

Here is a more general example showing a typical inner join with an ON clause:

<code class="language-csharp">var results = 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, db represents data context. The first line creates the alias Table1 for the table t1, and the second line creates the alias Table2 for the table t2. The on clause defines join conditions by matching the field attributes of both tables. The select statement specifies the fields of each table to be included in the result set. select new { ... } Create an anonymous type containing the fields of your choice.

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