65.9K
CodeProject is changing. Read more.
Home

Linq Join on Mutiple columns using Anonymous type

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (4 votes)

Oct 2, 2011

CPOL
viewsIcon

38212

Linq Join on Mutiple columns using Anonymous type

I was working on the project using LINQ. I got the requirement to join the two entities in multiple columns.

For example, consider the following image. There are two entities, Distributor and Customer related to each other.

Now I want to find out all customers who live in same city where the distributor lives.

So to find that out, I have to make a join between Customer and Distributor. And to achieve this, I need to join by using multiple columns City, State, Country, ID. (Note: I am using id in join because later on I want to get which distributor is near which customer).

Now with the LINQ, you can join two entities on multiple columns by creating one anonymous type.

EmployeeDataContext edb= new EmployeeDataContext();
var cust = from c in edb.Customers
           join d in edb.Distributors on
             new { CityID = c.CityId, StateID = c.StateId, CountryID = c.CountryId, 
                   Id = c.DistributorId }    
           equals
             new { CityID = d.CityId, StateID = d.StateId, CountryID = d.CountryId, 
                   Id = d.DistributorId }    
           select c;

Note: As anonymous types are used to join entities on multiple columns, make sure that both are equal and they must have the same properties in the same order. Otherwise it doesn't get complied and you get an error.

Once you are done, run the code and you will see the following query in your SQL profiler or you can also use the Visual Studio feature to get the query.

SELECT [t0].[Id], [t0].[Name], [t0].[EmailId], [t0].[CityId], [t0].[StateId], 
[t0].[CountryId], [t0].[PinCode], [t0].[DistributorId]
FROM [dbo].[Customer] AS [t0]
INNER JOIN 
[dbo].[Distributor] AS [t1] ON 
([t0].[CityId] = [t1].[CityId]) 
    AND ([t0].[StateId] = [t1].[StateId]) 
    AND  ([t0].[CountryId] = [t1].[CountryId]) 
    AND ([t0].[DistributorId] =[t1].[DistributorId])