【问题标题】:How do I return a table in LINQ that relies on a join/subquery?如何在 LINQ 中返回依赖于联接/子查询的表?
【发布时间】:2011-03-15 14:30:14
【问题描述】:

我需要 1 个表中的字段取决于另一个表中的 1 个属性匹配行。 我可以用这样的子查询在 SQL 中编写这个查询:

SELECT *
FROM Table1
WHERE Property1 IN
(
    SELECT Property1
    FROM Table2
    WHERE Property0 = 1
)

但我读到here 说它不那么复杂,而且用连接编写起来同样容易,我做到了。但是,到目前为止,由于我使用的是连接,因此我无法只返回 Table1,如果我没记错的话,它需要我创建这个匿名类型,如下所示。我在这里所做的工作(我创建了另一个具有我需要的 Table1 相同属性的对象),但我不禁想到有更好的方法来做到这一点。

Table1.Join(Table2, t1 => t1.Property1, t2 => t2.Property1, (t1, t2) => new
{
    t1.Property1,
    t1.Property2,
    t1.Property3
})
.Select(ob => new UnnecessaryObject
{
    Property1 = ob.Property1,
    Property2 = ob.Property2,
    Property3 = ob.Property3
}

我也尝试在 .Select 部分中创建一个 Table1,但我收到了关于不允许显式构造的错误。

澄清一下,我希望能够返回 Table1 类型的 IQueryable,这似乎我应该能够在不必创建 UnnecessaryObject 的情况下这样做......但我对 LINQ 还是很陌生,所以我很感激你能提供的任何帮助。提前致谢。

【问题讨论】:

    标签: linq linq-to-sql join subquery


    【解决方案1】:

    你可以这样做:

    from t1 in table1
    join t2 in table2 on t1.property1 equals t2.property1
    select t1;
    

    这将返回 table1 对象的集合。这假设您的示例 table1 是 table1 对象的集合,而 table2 是 table2 对象的集合。

    【讨论】:

    • 效果很好!非常感谢!
    【解决方案2】:

    我能想到的对您的原始查询的最佳翻译是:

    from item in context.Table1
    where context.Table2
        .Where(x => x.Property0 == 0)
        .Any(x => x.Property1 == item.Property1)
    select item
    

    这会从Table1 中选择所有项目,其中有一个项目与Table2 中的Property1Property0 == 0 匹配

    确实也可以通过join来解决。要获得有效的联接,您需要在两个表之间建立关系。然后你可以做一些事情,比如假设关系被称为RelatedItems

    from item in context.Table1
    join relatedItem in item.RelatedItems
        on item.Property1 equals relatedItem.Property
    where relatedItem.Property0 == 0
    
    select item
    

    这相当于SQL:

    SELECT * 
    FROM Table1
    JOIN Table2 ON Table1.Property1 = Table2.Property1
    WHERE Table2.Property0 = 0
    

    【讨论】:

    • 效果很好!非常感谢!
    猜你喜欢
    • 2012-06-21
    • 2019-07-07
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多