我正在尝试在我的查询中实现左连接,此时我正在获取'对象引用未设置为对象的实例' .
该查询完美地作为内部联接工作,但我想要包括左表中的所有行,即使找到了匹配项 . 我试图关注一些以前的帖子,大多数都引用了DefaultIfEmpty(),但我没有弄明白 .
INNER JOIN - SQL
SELECT TOP (1000)
FROM table1 as edc
inner join table2 as c on edc.Id = c.Id
inner join table3 as p on p.Id = c.Id
group by p.Description
INNER JOIN - SQL
SELECT TOP (1000)
FROM table1 as edc
inner join table2 as c on edc.Id = c.Id
left join table3 as p on p.Id = c.Id
group by p.Description
INNER JOIN - LINQ
from edc in table1
join q1 in table2 on __edc.Id equals q1__.Id
join q2 in _table3 on q2.Id equals q1.Id
group q1 by q2.Description
into grouped
select new MyObj
{
Label = grouped.Key,
Value = grouped.Count(),
}
LEFT JOIN - LINQ
from edc in table1
join q1 in table2 on __edc.Id equals q1__.Id
join q2 in _table3 on q2.Id equals q1.Id into leftJoin
from p in leftJoin.DefaultIfEmpty()
group q1 by p.Description
into grouped
select new MyObj
{
Label = grouped.Key,
Value = grouped.Count(),
}
2 回答
请考虑以下示例 . 我们有三个表,在table1和table2之间有一个左连接,第二个连接到table3 . 您需要在两个连接上指定
DefaultIfEmpty()
以包含右表中没有匹配的行 .运行该程序会产生以下输出:
希望这可以帮助!
它非常简单,只需将“从p”更改为“从q2”: