LINQ-to-SQLの基本は理解できましたが、JOINを適切に機能させるために苦労していました。次をLINQ-to-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
});