我试图在我的ASP.NET MVC项目中使用Entity Framework运行此查询,但我没有成功。任何人都可以帮我用LINQ做这个吗?
SELECT p.*
FROM Produtos p
WHERE p.enterpriseID = '00000000000191' and p.productId <> '14'
AND NOT EXISTS (SELECT 1 FROM SimilarProducts sp WHERE sp.similarId =
p.productId)
TABLES:
PRODUCT SIMILARPRODUCTS
productId|enterpriseId id|productId|similarId
答案 0 :(得分:13)
SQL NOT EXISTS (...)
的直接等效LINQ结构是!Any(...)
。
所以
SELECT p.*
FROM Produtos p
WHERE p.enterpriseID = '00000000000191' and p.productId <> '14'
AND NOT EXISTS (SELECT 1 FROM SimilarProducts sp WHERE sp.similarId =
p.productId)
转换为
from p in db.Produtos
where p.enterpriseID = "00000000000191" && p.productId != 14
&& !db.SimilarProducts.Any(sp => sp.similarId == p.productId)
select p;
答案 1 :(得分:4)
您可以将Contains
与Any
一起使用,它将在SQL中与NOT EXISTS
一样工作。像这样:
var restuls = db.Produtos.Where(p => p.enterpriseID == '00000000000191'
&& p.productId != 14
&& !db.SimilarProducts.Any(sp =>sp.SimilarId == p.productId));