如何将SQL中的多个内部连接转换为LINQ?
我已经掌握了LINQ到SQL的基本知识,但是我一直在努力让JOIN正常工作。 我想知道如何将以下转换为LINQ到SQL(理想情况下使用方法链,因为这是我的首选格式)。
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
使用查询语法:
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 });