简体   繁体   中英

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

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));

EF Contains => sql in() : iterate all items (slower)

EF Any => sql exists() : iterate until conditions return true (faster)

 await appDbContext.MasterTable
.Where(m => !m.DetailTable.Any(d => d.MasterId == m.Id))
.ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM