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

时间:2013-10-25 21:37:10

标签: c# linq

我有两张桌子:

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 PlacerTest One之外的所有内容,因为这两者都没有在客户端表中包含链接字段。

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

1 个答案:

答案 0 :(得分:4)

使用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中的左连接