How to write Linq (or lambda) statement to produce all element that are NOT IN (or NOT EXIST)
-
25-05-2021 - |
سؤال
Here is my scenario (Tables):
Orders
======================
Id (int)
description (varchar)
Products
======================
Id (int)
description (varchar)
OrderProductXREF (cross reference table)
======================
ProductId (int)
OrderId (int)
I think you get an idea. Nothing unusual is here.
When imported to EDMX file OrderProductXREF table is not visible entity. All I see is navigational properties: Products for entity Order and Orders for entity Product.
So, my problem: I need Linq and/or Lambda statement that will list all Products that don't have any Orders associated with. Or, list all Products that are never ordered.
SQL would go like this:
SELECT * FROM Products
WHERE Id NOT IN
(SELECT ProductId
FROM OrderProductXREF)
EDIT: Uh... sorry forgot one little detail in my question.
Here is the new SQL:
SELECT * FROM Products
WHERE Id NOT IN
(SELECT ProductId
FROM OrderProductXREF
WHERE OrderID = 1)
In words, All Products that are NOT ORDERED in order with ID = 1
Thanks
المحلول
Apologies - misread the question beforehand. I suspect you want:
var query = db.Products.Where(product => !product.Orders.Any());
You should definitely check the generated SQL though. I would expect it to be sensible, but if it's not, you would probably want to look at other alternatives.
EDIT: To check products not in order ID 1, you could probably use:
var query = db.Products.Except(db.Orders
.Where(order => order.Id == 1)
.Single()
.Products);
Or:
var query = db.Products.Where(product => !product.Orders
.Where(order => order.Id == 1)
.Any());
نصائح أخرى
var q = from p in Context.Products
where !p.Orders.Any()
select p;
Regarding your "one little detail":
var q = from p in Context.Products
where !p.Orders.Any(o => o.Id == 1)
select p;