How do I convert multiple inner joins in SQL to LINQ?

Solution 1:

Using query syntax:

from c in dbo.Companies
join p in dbo.Persons on c.AccountCoordinatorPersonId equals p.PersonId
join p2 in dbo.Persons on c.AccountManagerPersonId equals p2.PersonId
select new
{
    c.CompanyId,
    c.CompanyName,
    AccountCoordinator = p.FirstName + ' ' + p.Surname,
    AccountManager = p2.FirstName + ' ' + p2.Surname
}

Using method chaining:

dbo.Companies.Join(dbo.Persons, 
                   c => c.AccountCoordinatorPersonId,  
                   p => p.PersonId,  
                   (c, p) => new 
                   {  
                       Company = c,  
                       AccountCoordinator = p.FirstName + ' ' + p.Surname  
                   })
             .Join(dbo.Persons,  
                   c => c.Company.AccountManagerPersonId,  
                   p2 => p2.PersonId,  
                   (c, p2) => new 
                   {  
                       c.Company.CompanyId,  
                       c.Company.CompanyName,  
                       c.AccountCoordinator,  
                       AccountManager = p2.FirstName + ' ' + p2.Surname 
                   });