【问题标题】:ASP.net -Trying to associate one primary key to multiple foreign keysASP.net - 尝试将一个主键关联到多个外键
【发布时间】:2012-10-11 13:45:47
【问题描述】:

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

之前,我将 Ingreients recipeID 分配给与目标 Recipes recipeID 相同的值。然而,这限制了成分与单个配方相关联。

通过将 Recipes 的成分 ID 与一种成分相关联,Recipe 似乎只能与一种成分相关联,但该成分可以与其他食谱相关联。

我尝试创建一个 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; }

我试图实现的最后一个概念是用户在食谱编辑视图中选择一种成分,选择之前已经添加的成分并单击保存以将其与该特定食谱相关联,但也可以转到同时将其与更多食谱相关联。

非常感谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    这样食谱可以通过RecipeIngredients 表有多种成分,并且仍然有一个表(Ingredient)表示每个元组1 个成分和每个元组1 个食谱(Recipe)。

    LMK 如果有帮助:)

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多