Question

I'm trying to write a semi convoluted query :-

The query should select a random selection of rows from a table which do not have a matching entry in a linking table. I.e

dishes
----
id
name


food
----
id
name

foodInDishes
----
food_id
dish_id

So what I am trying to accomplish is select the top most 10 rows where a user does not have a specific food. So

"Give me 10 dishes that I can make which do not contain carrots"

In C# I have a List<int> of foods to avoid. So far I have got too :-

List<int> oFoodsToAvoid = new List<int>();
var oDishes= db.dishes.OrderBy(r => Guid.NewGuid()).Take(10);

However I am struggling with the foods to avoid where clause. The problem I am facing is because it's a child table (i.e items.foods.id ). Any suggestions on what the where clause should contain?

Was it helpful?

Solution

You can use a simple nested lambda to achieve this. If oFoodsToAvoid is large, you could probably sort it before querying and then use Array.BinarySearch() in your nested lambda:

List<int> oFoodsToAvoid = new List<int>();
var oDishes= db.dishes.Where(d => !d.foods.Any(df => oFoodsToAvoid.Any(arr => arr == df.food_id)))
                       .OrderBy(r => Guid.NewGuid()).Take(10);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top