C# Linq查询联接不工作
嗨,我正在尝试连接c中的两个表。下面给出了连接代码。问题是,当tb_abc中tourid的值为空时,in将不会将tb_abc中的该行包括在列表中C# Linq查询联接不工作,c#,asp.net,linq,C#,Asp.net,Linq,嗨,我正在尝试连接c中的两个表。下面给出了连接代码。问题是,当tb_abc中tourid的值为空时,in将不会将tb_abc中的该行包括在列表中 return (from p in context.tb_abc from o in context.tb_Second where o.id==p.tourId where p.driverId == driverId
return (from p in context.tb_abc
from o in context.tb_Second
where o.id==p.tourId
where p.driverId == driverId
select new abcBean
{
id=p.id,
name=o.name
}).ToList<abcBean>();
有人能告诉我我做错了什么吗您在该查询中没有进行内部联接。您正在进行交叉连接,在这里您有两个表,并将每个记录连接到每个其他记录 如果要包括在其中一个约束上返回null的行,则需要左外部联接
return (from p in tb_abc
join o in tb_Second on p.tourId equals o.id into po
where p.driverId == driverId
from subpo in po.DefaultIfEmpty()
select new abcBean
{
id=p.id,
name=(subpo == null ? String.Empty : subpo.Name)
}).ToList();
考虑以下两条sql语句:
第一个是交叉连接:
select id, name
from tb_abc o,
tb_Second p
where
o.id = p.tourID
and p.driverID = @driverID
第二个是左外连接:
select id, name
from tb_abc o
LEFT OUTER JOIN tb_Second p on o.id = p.tourID
where
p.driverId = @driverID
第二个将为您提供一组记录,其中包括o.id的空值
第一个会给你一些你很少想要的东西
如果Linq的DefaultIfEmpty没有找到与一侧匹配的值,则会将默认值null放入记录中,因此它的行为类似于左外部联接。您可以像这样使用左外部联接
return (from p in tb_abc
join o in tb_Second on p.tourId equals o.id into po
where p.driverId == driverId
from subpo in po.DefaultIfEmpty()
select new abcBean
{
id=p.id,
name=(subpo == null ? String.Empty : subpo.Name)
}).ToList();
return (from p in context.tb_abc
join o in context.tb_Second on o.id==p.tourId into gt
where p.driverId == driverId
from subsecond in gt.DefaultIfEmpty()
select new abcBean
{
id=p.id,
name=(subsecond == null ? String.Empty : subsecond.Name)
}).ToList<abcBean>();
因为它不会编译,所以首先使用o.id变量,并在线使用一个=。您需要将其更改为p.tourId=o.idi我的交叉连接示例不是真正的交叉连接,因为我们在where子句中连接表,所以有一些限制。如果没有约束,它将使用sql89语法进行交叉连接。