Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

How to Join Multiple Columns with Linq To SQL

5.00/5 (1 vote)
27 Jan 2012CPOL 49K  
How to join multiple columns with Linq to SQL

Today, I had to create a Linq-To-SQL query which joined two tables. These tables had compound primary keys (table simplified for example):

Table Referrers

ServerID (PK)ReferrerID (PK)Value
11My value 1
12My value 2
13My value 3

Table ReferrerInfo

ServerID (PK)ReferrerID (PK)Value
11More info… 1
12More info… 2
13More Info… 3

So I wanted to join these together using a Linq-To-SQL query. The first thought that occurred to me was to use a join:

C#
var referrers = from r in Referrers
              join ri in ReferrerInfo on r.ServerConnectionID equals ri.ServerConnectionID ..... ??????
              select r;

So, apparently in C#, you cannot do multiple columns in your join. I have to join on both ServerConnectionID and ReferrerID.

This page http://www.onedotnetway.com/linq-to-sql-join-on-multiple-conditions/ explains one method to do so, but unfortunately that Linq query only works in VB.

So, I ended up writing a Linq-To-SQL that just uses the old style of joining, by using the where clause!

C#
var referrers = from r in Referrers
                from ri in Referrer_Info
                where r.ServerConnectionID == ri.ServerConnectionID &&
                   r.ReferrerID == ri.ReferrerID
                select r;

This successfully executes my multi-column join.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)