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

标签 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 不能有 where)。有关于使用多个 from 子句的讨论,但是如果我创建了多个 from 子句,那么我可以在第二个子句中添加一个 where,我不知道如何加入它们的结果到一个新的临时表中。

我不能只在连接后添加一个“where”;必须先过滤右表,否则会发生匹配,末尾的 where 子句将从左表中删除我希望在输出中显示的行。也就是说,输出应该包含从过滤后的右表中没有任何匹配项的行。所以我需要在连接之前过滤正确的表。

最佳答案

我认为您正在寻求这样做:

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 ....

关于entity-framework - Linq to SQL 自联接,其中联接的右侧部分被过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345711/

相关文章:

php - 类似 Entity Framework 的 ORM 不适用于 .NET

c# - 当另一个属性更改时更新实体属性(实体初始化后)

c# - LINQ 查询速度慢,创建超时;生成的 SQL 没问题?

linq-to-sql - 定义与 LinqToSQL 的一对一关系

sql - LINQ to SQL SOUNDEX - 可能吗?

asp.net - 在 EF 的自联接表中选择最后一个 child

entity-framework - 在哪里可以找到 ADO.NET Entity Framework 错误列表?

entity-framework - 如何在 Entity Framework 5 中增加/减少多用户安全

asp.net - 从 DataContext 缓存数据

c# - 为什么 LINQ-to-SQL 分页在函数内失败?