[LINQ].NET/C#应用程序编程开发中如何将多表内连接的SQL转换成对应的LINQ查询?

C#开发 作者: Rector 46阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

问题描述

假设当前有一条多表关联(内连接)查询的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

在.NET/C#应用程序编程开发中,现需要将以上的多表关联SQL查询语句转换成对应的LINQ查询,应该如何实现呢?

方案一

使用LINQ的查询语句实现,如下:

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
}

方案二

使用LINQ的扩展方法实现,如下:

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

阅读了该文章的人还浏览了...

本文永久链接码友网 » [LINQ].NET/C#应用程序编程开发中如何将多表内连接的SQL转换成对应的LINQ查询?

发布于: 2018-07-23 10:31:20
分享扩散: