Skip to main content
 首页 » 编程设计

c#之需要左外连接类型时在 LINQ 中连接表的问题

2024年02月13日17zhwl

我有两个表:

Network_Clients 
Clients 

Network_Clients 有三列

networkClientID: Key 
Name: Varchar 
Description: Varchar 

客户端有 4 列:

clientID: Key 
networkClientId: FK to Network_Clients -> networkClientID 
Name: Varchar 
Description: Varchar 

客户表:

clientID    networkClientID name    description 
1                2          Client1 Client of Client2 
2                3          Client1 Client of Client3 
3                3          Client4 Client of Client3 
4                1          Client4 Direct Placement Client 
5                1          Client1 Direct Placement Client 

网络客户端表:

networkClientID name            description 
1           Direct Placer       NULL 
2           Client2             Network Client Client2 
3           Client3             Network Client Client3 
4           Test One            Test One Network Client 

这是我的 LINQ 查询:

from cn in Clients_Network 
join c in Clients on cn.networkClientID equals c.networkClientID 
select new { cn, c } 

这将返回除 Direct Placer 和 Test One 之外的所有内容,因为它们在 Clients 表中都没有链接字段。

我怎样才能让这两个出现?

请您参考如下方法:

使用group join (即加入...进入):

from cn in Clients_Network 
join c in Clients on cn.networkClientID equals c.networkClientID into g 
from cc in g.DefaultIfEmpty() 
select new { cn, cc } 

这相当于 SQL 中的左连接