【发布时间】:2011-11-24 10:03:20
【问题描述】:
如何在 linq 中编写下面的 sql 查询
select * from Product where ProductTypePartyID IN
(
select Id from ProductTypeParty where PartyId = 34
)
【问题讨论】:
标签: sql-server linq entity-framework
如何在 linq 中编写下面的 sql 查询
select * from Product where ProductTypePartyID IN
(
select Id from ProductTypeParty where PartyId = 34
)
【问题讨论】:
标签: sql-server linq entity-framework
在 LINQ 中没有直接的等价物。相反,您可以使用 contains () 或任何
实现它们的其他技巧。这是一个使用Contains的示例:
String [] s = new String [5];
s [0] = "34";
s [1] = "12";
s [2] = "55";
s [3] = "4";
s [4] = "61";
var result = from d in context.TableName
where s.Contains (d.fieldname)
select d;
查看此链接了解详情:in clause Linq
int[] productList = new int[] { 1, 2, 3, 4 };
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
【讨论】:
抛开句法变化不谈,你可以用几乎相同的方式编写它。
from p in ctx.Product
where (from ptp in ctx.ProductTypeParty
where ptp.PartyId == 34
select ptp.Id).Contains(p.ProductTypePartyID)
select p
不过,我更喜欢使用存在量词:
from p in ctx.Product
where (from ptp in ctx.ProductTypeParty
where ptp.PartyId == 34
&& ptp.Id == p.ProductTypePartyID).Any()
select p
我希望此表单将解析为生成的 SQL 中的 EXISTS (SELECT * ...)。
您需要对两者进行分析,以防性能差异很大。
【讨论】:
类似的东西
var partyProducts = from p in dbo.Product
join pt in dbo.ProductTypeParty on p.ProductTypePartyID equal pt.PartyId
where pt.PartyId = 34
select p
【讨论】:
您在 Where 子句中使用 Contains。
类似的东西(未经测试):
var results = Product.Where(product => ProductTypeParty
.Where(ptp => ptp.PartyId == 34)
.Select(ptp => ptp.Id)
.Contains(product.Id)
);
【讨论】: