I have the following table:
recipe
id | ingredients
----+--------------
1 | "1,2,3"
2 | "3,4"
3 | "2"
4 | "1,2,3,4"
I want to find all recipes containing ingredient "1", "3" or "4". How can I achieve that using Entity Framework Core?
Here’s what I’ve tried, but it seems like this expression is not translatable:
var ingredientIds = new List<string> {"1", "3", "4"};
var recipes = dbContext.Set<Recipe>
.Where(x => x.IngredientIds.Split(',', StringSplitOptions.None).Any(y => ingredientIds.Contains(y))
.ToList();
2
Answers
Well, you shouldn’t be using comma delimited values in the first place, that’s what’s causing your problem.
The solution would be to change the database design to create a proper many-to-many relationship between recipe and ingredients.
In a DB first design, you’ll add an IngredientToRecipe table:
In a Code first design, you’ll have to add navigation properties to your entities as collections:
EF Core will know how to translate this to a many-to-many relationship.
outputs (when using the data from you other question: Entity Framework Core : join comma-separated list ):
EDIT: When ingredient like
100
, or any ingredient with more than 1 digit, is added a small change is needed in the where part: