I’m working on a C# project and need help with LINQ to SQL. I want to do an inner join between two tables, but I’m not sure about the correct syntax.
Here’s what I’m trying to achieve:
I have a Dealer table and a DealerContact table. I want to get all the DealerContact info for each Dealer where their DealerID matches. In regular SQL, it would look something like this:
SELECT DealerContact.*
FROM Dealer
INNER JOIN DealerContact ON Dealer.DealerID = DealerContact.DealerID
Can someone show me how to write this using LINQ to SQL? I’ve tried a few things, but they’re not working right. Any help would be great. Thanks!
To perform an inner join using LINQ to SQL in C#, you can utilize the join clause in combination with the equals keyword. Here’s an efficient approach:
var result = from dealer in context.Dealers
join contact in context.DealerContacts
on dealer.DealerID equals contact.DealerID
select contact;
This query will return all DealerContact records that have a matching DealerID in the Dealer table. You can then iterate through the result set to access the joined data. Remember to replace ‘context’ with your actual DataContext name.
For better performance, consider using compiled queries if you’ll be executing this join frequently.