Linq to SQL自联接,其中右侧部分被过滤

时间:2013-01-15 19:52:38

标签: entity-framework linq-to-sql

我正在尝试映射必须过滤右表的自联接,例如这样的SQL:

select t2.* from table t 
    left join table t2 
    on t2.parentID = t.ID and t2.active=1;

如果我想过滤 left 表,我可以弄清楚语法:

// works
var query = from t in table
               where t.active= 1
            join t2 in table
               on t.parentID equals t2.ID into joined
            from r in joined.DefaultIfEmpty() ...

但我无法弄清楚如何过滤正确的表格。看起来它应该是这样的......

// does not work
var query = from t in table
            join t2 in table
               where t.field = 1
               on t.parentID equals t2.ID into joined
            from r in joined.DefaultIfEmpty() ...

(无效...... join不能有位置)。有关使用多个from子句的讨论,但是如果我创建多个from子句,那么我可以在第二个中添加where,我无法弄清楚如何将它们的结果加入到新的临时表。

我不能在加入后添加“where”;必须首先过滤正确的表,否则将发生匹配,最后的where子句将从输出中删除左表中的行。也就是说,输出应该有行,其中没有与过滤的右表匹配。所以我需要在加入之前过滤右表。

1 个答案:

答案 0 :(得分:3)

我认为你希望这样做:

var query = from t in table
            join t2 in 
               (from t3 in table
                where t3.field = 1
                select t3)
               on t.parentID equals t2.ID into joined
            from r in joined.DefaultIfEmpty() ...

另一种方法是使用多个from,如下所示:

var query = from t in table
            from t2 in table.Where(x => x.field = 1)
                            .Where(x => x.ID == t.parentID)
                            .DefaultIfEmpty()
            select ....