处理 LINQ to SQL 中的 IN 子查询
在 LINQ to SQL 中利用 IN 子查询是关联数据的有效方法来自多个表。实现方法如下:
常规 IN 查询实现:
要在 LINQ to SQL 中实现 IN 查询,请遵循以下语法:
var q = from t1 in table1 let t2s = from t2 in table2 where <Conditions for table2> select t2.KeyField where t2s.Contains(t1.KeyField) select t1;
具体示例:
让我们重新查看示例 SQL 查询:
SELECT f.* FROM Foo f WHERE f.FooId IN ( SELECT fb.FooId FROM FooBar fb WHERE fb.BarId = 1000 )
在 LINQ to SQL 中,这将转换为:
var query = from f in db.Foo let fubars = from fb in db.FooBar where fb.BarId == 1000 select fb.FooId where fubars.Contains(f.FooId) select f;
其他注意事项:
对于EXISTS 查询,您可以使用 Any() 方法而不是包含():
var q = from t1 in table1 let t2s = from t2 in table2 where <Conditions for table2> select t2.KeyField where t2s.Any(t1.KeyField) select t1;
以上是如何在LINQ to SQL中高效实现IN子查询?的详细内容。更多信息请关注PHP中文网其他相关文章!