I have 2 tables, one Orders and one Products. The Orders has OrderID, OrderName and AccessID, whilst the Products has ProductID, ProductName and OrderID. These tables have more fields but these are the relevant ones for my problem.
So what I wish to do is, get the first set of products in the products table with their OrderID, which order has less than 8 products, and the AccessID is 1.
I know that I can do it in 2 LINQ statements, first filter by AccessID in Orders, and then create a loop in the products table to get the first instance of Count < 8, however I am sure there is a better way to do this, possibly in 1 statement.
Thanks for your help and time
This is what I have come up with for now and still has to be tested :-
public Order OrdersLessThanEightItems()
{
IEnumerable<int> orderId = null;
int accessID = 1;
Order order = (from o in db.Orders
where o.AccessID == accessID && o.Products.Count < 8
orderby o.Products.Count ascending
select o).FirstOrDefault();
return order;
}
Pre Edit
Shouldn’t the relationship between orders and products be a many to many relationship?
Should product have OrderID? Then 1 product will only allowed to be in 1 order.
Post Edit (after highlighting that the relationship is 1 to many)
Then you’ll be able to use this (untested):