如何在LINQ中返回依赖于联接/子查询的表?
我需要一个表中的字段取决于另一个表中匹配行的一个属性。 我可以用SQL编写此查询,并使用如下子查询:如何在LINQ中返回依赖于联接/子查询的表?,linq,linq-to-sql,join,subquery,Linq,Linq To Sql,Join,Subquery,我需要一个表中的字段取决于另一个表中匹配行的一个属性。 我可以用SQL编写此查询,并使用如下子查询: SELECT * FROM Table1 WHERE Property1 IN ( SELECT Property1 FROM Table2 WHERE Property0 = 1 ) 但我读到,它不那么复杂,而且用join编写起来也一样简单,我就是这么做的。然而,到目前为止,由于我使用的是联接,所以我无法按我所希望的那样仅返回Table1,如果我没有弄错的话,这需要我
SELECT *
FROM Table1
WHERE Property1 IN
(
SELECT Property1
FROM Table2
WHERE Property0 = 1
)
但我读到,它不那么复杂,而且用join编写起来也一样简单,我就是这么做的。然而,到目前为止,由于我使用的是联接,所以我无法按我所希望的那样仅返回Table1,如果我没有弄错的话,这需要我创建这个匿名类型,如下所示。我在这里所做的工作是有效的(我创建了另一个具有表1相同属性的对象,我需要),但我忍不住想有更好的方法来实现这一点
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,这似乎是我应该能够做到的,而不必创建不必要的对象…但我对LINQ还是相当陌生,所以我非常感谢您提供的任何帮助。提前谢谢。您可以:
from t1 in table1
join t2 in table2 on t1.property1 equals t2.property1
select t1;
这将返回table1对象的集合。根据示例,假设table1是table1对象的集合,table2是table2对象的集合。您可以执行以下操作:
from t1 in table1
join t2 in table2 on t1.property1 equals t2.property1
select t1;
这将返回table1对象的集合。根据示例,假设table1是table1对象的集合,table2是table2对象的集合。我能想到的原始查询的最佳翻译是:
from item in context.Table1
where context.Table2
.Where(x => x.Property0 == 0)
.Any(x => x.Property1 == item.Property1)
select item
这将从表1
中选择所有项目,其中有一个项目与表2中的属性1
和属性0==0
相匹配
它也可以通过连接来解决。要获得有效的联接,需要在两个表之间建立关系。然后,您可以做一些类似于假设关系被称为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
我能想到的对您原始查询的最佳翻译是:
from item in context.Table1
where context.Table2
.Where(x => x.Property0 == 0)
.Any(x => x.Property1 == item.Property1)
select item
这将从表1
中选择所有项目,其中有一个项目与表2中的属性1
和属性0==0
相匹配
它也可以通过连接来解决。要获得有效的联接,需要在两个表之间建立关系。然后,您可以做一些类似于假设关系被称为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
工作得很好!非常感谢!工作得很好!非常感谢!工作得很好!非常感谢!工作得很好!非常感谢!