Linq通过Linq2db将外部联接排除在外

时间:2018-02-04 16:24:54

标签: vb.net linq ms-access linq2db

使用Linq2dbMs Access我想选择所有没有目标的行业我想要执行左外连接并排除:

Dim q10 = From s In db.Sectors
          From t In db.Targets.Where(Function(f) f.id_sector = s.Id).DefaultIfEmpty
          Where t Is Nothing
          Select s

Linq2db将此解析为:

--  Access
SELECT
    [t2].[Id],
    [t2].[Name]
FROM
    [tblSector] [t2]
        LEFT JOIN [tblTarget] [t1] ON ([t1].[id_sector] = [t2].[Id])
WHERE
    [t1].* IS NULL <=========== HERE

这显然是错误的。

我也试过了:

Dim q10 = From s In db.Sectors
          From t In db.Targets.Where(Function(f) f.id_sector = s.Id And f Is Nothing).DefaultIfEmpty
          Select s

接收:

--  Access
SELECT
    [t2].[Id],
    [t2].[Name]
FROM
    [tblSector] [t2]
        LEFT JOIN [tblTarget] [t1] ON ([t1].[id_sector] = [t2].[Id] AND [t1].* IS NULL) <=========== HERE

总结一下,我需要:

SELECT
    [t2].[Id],
    [t2].[Name]
FROM
    [tblSector] [t2]
        LEFT JOIN [tblTarget] [t1] ON ([t1].[id_sector] = [t2].[Id])
WHERE
    [t1].[id_sector] IS NULL

如何在Where t1.id_sector Is Nothing条件下撰写(id_sector为FK,因此它为Integer,因此无法Nothing

1 个答案:

答案 0 :(得分:0)

我找到了答案。这是一个小小的解决方法,但它确实有效。

因为此查询在linq2db中无效:

Dim q10 = From s In db.Sectors
          From t In db.Targets.Where(Function(f) f.id_sector = s.Id).DefaultIfEmpty
          Where t Is Nothing
          Select s

相反,我们可以这样写:

Dim q10 = From s In db.Sectors 
          Where Not (From t In db.Targets Select t.id_sector).Contains(s.Id)
          Select s

然而生成的SQL看起来像这样:

SELECT
    [t2].[Id],
    [t2].[Name]
FROM
    [tblSector] [t2]
        LEFT JOIN [tblTarget] [t1] ON ([t1].[id_sector] = [t2].[Id])
WHERE
    [t1].[id_sector] IS NULL

看起来像这样:

SELECT
    [t2].[Id],
    [t2].[Name]
FROM
    [tblSector] [t2]
WHERE
    NOT (EXISTS(
        SELECT
            *
        FROM
            [tblTarget] [t1]
        WHERE
            [t1].[id_sector] = [t2].[Id]
    ))