LINQ to SQL offers a streamlined approach to executing SQL queries within C#. A frequent requirement is the inner join, merging data from multiple tables based on a matching condition.
LINQ to SQL Syntax:
The structure for an inner join utilizing an ON clause 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</code>
Illustrative Example:
Consider this SQL query:
<code class="language-sql">select DealerContact.* from Dealer inner join DealerContact on Dealer.DealerID = DealerContact.DealerID</code>
Equivalent LINQ to SQL Query:
<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>
This LINQ query achieves the same result:
dealercontacts
stores the query's output.db.DealerContact
references the first table.db.Dealer
references the second table.contact.DealerId
and dealer.Id
are the join keys.Important Consideration:
It's crucial to verify that the table and field names in your LINQ query precisely align with your database schema. Any discrepancies will lead to errors.
The above is the detailed content of How to Perform an Inner Join with an ON Clause Using LINQ to SQL?. For more information, please follow other related articles on the PHP Chinese website!