ASP.net - 尝试将一个主键与多个外键相关联

时间:2012-10-11 13:45:47

标签: .net asp.net-mvc entity-framework

我有一个包含主键的成分列表:ingredientID和外键:recipeID。我一直试图将单个成分映射到许多食谱,每个食谱都包含一个recipeID和一个成分ID。

以前,我将Ingreients recipeID指定为与目标Recipes recipeID相同。这限制了成分与单一食谱相关联。

通过将食谱配方ID与成分相关联,似乎食谱只能与其中一种成分相关联,但该成分可与其他配方相关联。

我尝试创建一个recipeIngredient,其中包含一个recipeID和一个要素ID,用于关联食谱和配料,但我没有成功。

以下是对当前模型的描述。

食谱模型:

    [Key]
    public int recipeID { get; set; }
    public int ingredientID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Cost { get; set; }

    public virtual NutritionalValue NutritionalDetails { get; set; }
    public virtual ICollection<Ingredient> Ingredients { get; set; }
    public virtual ICollection<RecipeStep> RecipieSteps { get; set; }

成分模型:

    [Key]
    public int ingredientID { get; set; }
    //public int recipeID { get; set; }
    public string Name { get; set; }
    public string Descritpion { get; set; }
    public decimal Cost { get; set; }
    public decimal Amount { get; set; }
    public string Type { get; set; }

    public virtual Recipe Recipe { get; set; }

我想要实现的最终概念是用户在食谱编辑视图中选择一种成分,选择之前已添加的成分并单击保存以将其与特定食谱相关联,但也可以去同时将其与其他食谱联系起来。

非常感谢。

1 个答案:

答案 0 :(得分:0)

据我所知,您希望每个配方都有多种成分,但您希望有一个不重复条目的成分表。这实际上更像是一对多关系。如果是这种情况,您的数据库架构需要更改为:

Ingredient(id (pk), name, etc...)
Recipe(id (pk), name, etc...)
RecipeIngredients(recipeId (fk to Recipe.id), ingredientId (fk to ingredient.id))

这样食谱可以通过RecipeIngredients表有多种成分,还有一个表(成分)代表每个元组1个成分和每个元组1个食谱(食谱)。

LMK如果有帮助:)