2010-11-06 79 views
58

我已經掌握了LINQ-to-SQL的基礎知識,但我一直在努力嘗試讓JOIN正常工作。我想知道如何將以下內容轉換爲LINQ-to-SQL(理想情況下使用方法鏈接,因爲這是我的首選格式)。如何將SQL中的多個內部連接轉換爲LINQ?

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 

回答

132

使用查詢語法:

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 
} 

使用方法鏈接:

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

感謝非常真棒例子......還是有用的5年後! – 2014-03-07 18:01:48

相關問題