我有下表:
recipe
id | ingredients
----+--------------
1 | "1,2,3"
2 | "3,4"
3 | "2"
4 | "1,2,3,4"
我想找到所有含有成分“1”、“3”或“4”的食谱。如何使用 Entity Framework Core 实现这一目标?
这是我尝试过的,但似乎这个表达不可翻译:
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();
嗯,您首先不应该使用逗号分隔值,这就是导致问题的原因。
解决方案是更改数据库设计,以在配方和成分之间创建适当的多对多关系。
在数据库优先设计中,您将添加一个 IngredientToRecipe 表:
CREATE TABLE IngredientToRecipe
(
recepieId int NOT NULL,
IngredientId int NOT NULL,
CONTRAINT PrimaryKey Pk_IngredientToRecipe (recepieId, IngredientId)
)
在代码优先设计中,您必须将导航属性作为集合添加到实体中:
class Recipe
{
public List<Ingredient> Ingredients {get;set;}
// other properties here
}
class Ingredient
{
public List<Recipe> Recipes {get;set;}
// other properties here
}
var newrecipes = (from r1 in recipes
from i in ingredients
where r1.IngredientIds.Contains(i.Id.ToString())
select new { recipe = r1.Id, ingedientId = i.Id, ingredientName = i.Name }
);
foreach (var item in newrecipes )
{
System.Console.WriteLine($"recipe {item.recipe}: ingredient: {item.ingedientId}, {item.ingredientName}");
}
输出(当使用您其他问题的数据时:Entity Framework - Join Comma Separed List):
recipe 1: ingredient: 1, flour
recipe 1: ingredient: 2, sugar
recipe 1: ingredient: 3, egg
recipe 2: ingredient: 3, egg
recipe 2: ingredient: 4, butter
recipe 3: ingredient: 2, sugar
recipe 4: ingredient: 1, flour
recipe 4: ingredient: 2, sugar
recipe 4: ingredient: 3, egg
recipe 4: ingredient: 4, butter