Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

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

I've got the basics of LINQ-to-SQL down, but I've been struggling trying to get JOINs to work properly. I'd like to know how to convert the following to LINQ-to-SQL (ideally using method chaining, as that is my preferred format).

SELECT      c.CompanyId, c.CompanyName,
            p.FirstName + ' ' + p.LastName as AccountCoordinator,
            p2.FirstName + ' ' + p2.LastName as AccountManager
FROM        dbo.Companies c
INNER JOIN  dbo.Persons p
ON          c.AccountCoordinatorPersonId = p.PersonId
INNER JOIN  dbo.Persons p2
ON          c.AccountManagerPersonId = p2.PersonId
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 
                   });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...