Skip to content
Advertisement

EF – AND NOT EXISTS (SELECT 1 …) with Entity Framework

I am trying to run this query using Entity Framework in my ASP.NET MVC project but I am not succeeding. Could anyone help me do this using 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

Advertisement

Answer

The direct equivalent LINQ construct of SQL NOT EXISTS (...) is !Any(...).

So

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)

translates to

from p in db.Produtos
where p.enterpriseID = "00000000000191" && p.productId != 14 
&& !db.SimilarProducts.Any(sp => sp.similarId == p.productId)
select p;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement