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
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;
You can use Contains
with Any
which will work like NOT EXISTS
in SQL. Like this:
var restuls = db.Produtos.Where(p => p.enterpriseID == '00000000000191'
&& p.productId != 14
&& !db.SimilarProducts.Any(sp =>sp.SimilarId == p.productId));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With