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).
我已经掌握了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
1 个解决方案
#1
133
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
});
#1
133
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
});