将SQL转换为Linq以进行左连接,右侧为NULL

时间:2017-07-17 17:14:47

标签: c# sql-server linq

如何将以下SQL语句转换为Linq:

GCM

我写了以下但是我无法弄清楚如何添加" OR B.Filter是NULL"它:

SELECT A.Application, B.Filter
FROM Applications A left join Filters B on A.Application = B.Filter OR 
B.Filter is null

例如,如果Applications和Filter表格如下:

var filteredApproved = (from f in 
(from a in Applications
join b in Filters on a.Application equals b.Filter into rss
from ss in rss.DefaultIfEmpty()
select new {
a.Application,
Filter = (b == null ? 0: b.Filter)
})

我想要以下结果

Application
---------
A
B

Filter
--------
A
null

Linq查询返回:

Application   Filter
---------     ------
A             A
A             null
B             null

它不返回SQL返回的第二行。我需要添加"或B.Filter为NULL"来到linq。

1 个答案:

答案 0 :(得分:2)

LINQ仅支持 equijoins 。其他类型连接的唯一选项是相关where(常规where,条件访问两个相关序列的属性),或者在left outer join的情况下 - 相关子查询:< / p>

var result =
    from a in Applications
    from b in Filters
        .Where(b => a.Application == b.Filter || b.Filter == null)
        .DefaultIfEmpty()
    select new
    {
        a.Application,
        Filter = b == null ? null : b.Filter
    };