使用实体框架的EF - AND NOT EXISTS(SELECT 1 ...)

时间:2015-11-05 13:09:29

标签: c# sql asp.net-mvc entity-framework linq

我试图在我的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

2 个答案:

答案 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)

您可以将ContainsAny一起使用,它将在SQL中与NOT EXISTS一样工作。像这样:

var restuls = db.Produtos.Where(p => p.enterpriseID == '00000000000191' 
                 && p.productId != 14 
                 && !db.SimilarProducts.Any(sp =>sp.SimilarId == p.productId));