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

How to Perform Inner Joins in LINQ to SQL?

DDD
Release: 2025-01-21 00:40:08
Original
487 people have browsed it

How to Perform Inner Joins in LINQ to SQL?

Using LINQ to SQL for inner joins

Joining tables is a basic task when processing data in a relational database. LINQ to SQL provides a convenient way to perform inner joins, allowing you to retrieve data from multiple tables based on a common key.

Inner join syntax

The syntax of inner join in LINQ to SQL 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>
Copy after login

In this syntax:

  • t1 and t2 are variables representing the tables to be joined.
  • on t1.field equals t2.field is a join condition specifying that the two tables should be joined based on equality of the specified fields.
  • The
  • select clause specifies the columns in the join table that should 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>
Copy after login

This query performs an inner join on the DealerID and Dealer tables based on the DealerContact column. To represent this query in LINQ to SQL, you can use the following code:

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

In this example, the DealerContact table is selected as the primary table and the Dealer tables are joined based on the DealerId columns. The result is a collection of DealerContact objects containing data from both tables.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template