首页 > 解决方案 > 关系数据库:数据库结构/流程

问题描述

我正在使用实体框架来设置数据库。我是关系数据库的新手,我正在尝试确定设置几个表及其关系的正确方法。这是独家新闻。

假设我的数据库中有三个表。

主表是表 A,它包含一个对象的数据集,我们称之为这个对象Food。列:(FoodID主键)、RecipeID(与表 C 中的配方配对的外键)。

表 C:包含用于制作Food存储在表 A 中的不同项目的配方记录。列:RecipeID(主键)和配方名称。

表 B:是用于创建Food. 列:EntryID(主键)、RecipeID(外键引用表 C 中的食谱 ID)、FoodID(外键引用表 A 中的食物)。

我无法围绕正确的方法来做这件事,因为它是一种循环关系。

我只是从表中删除外键( RecipeID)吗?Food在这种情况下,我应该追求的正确流程是什么。

 Recipes -> Multiple Recipe Entries -> Food -> Recipe

Food需要一个配方来制作它,但Food在配方中用于制作其他Food.

将数据概念化为 C# 代码,它看起来像这样。

public class Food
{
    public int FoodID { get; set; }
    public string Name { get; set; }
    public List<Food> Recipe { get; set; }
}

实体框架模型如下。

public class Food
{
    [Key]
    public int FoodID { get; set; }//Pri Key
    public string Name { get; set; }
    public int FoodRecipeID { get; set; }//Foreign Key

    public virtual FoodRecipe FoodRecipe { get; set; }//Navigation Property
}

public class FoodRecipeEntry
{
    [Key] 
    public int FoodRecipeEntryId { get; set; } //Pri Key
    public string Name { get; set; }
    public int FoodID { get; set; }//Foreign Key
    public int FoodRecipeID { get; set; }

    //Navigation Properties
    public Food Food { get; set; }
    public FoodRecipe FoodRecipe { get; set; }
}

public class FoodRecipe
{
    [Key]
    public int FoodRecipeID { get; set; } //Pri Key
    public string Name { get; set; }
    public virtual ICollection<FoodRecipeEntry> FoodRecipeEntries {get; set; }//Navigation Property
}

标签: c#sql-serverdatabaseentity-framework-core

解决方案


这里有一些提示:

  1. 从 中删除食物 ID FoodRecipeEntry,由于食谱是针对特定食物的,因此食谱隐含了 FoodID,并且该条目属于给定食谱
  2. 我个人将外键放在食谱中,而不是食物 - 一种食物可能有多个食谱,所以它应该是食谱 - >食物

在代码中,这看起来像这样:

public class Food
{
    [Key]
    public int FoodID { get; set; }//Pri Key
    public string Name { get; set; }

    public virtual FoodRecipe FoodRecipe { get; set; }//Navigation Property
}

public class FoodRecipeEntry
{
    [Key] 
    public int FoodRecipeEntryId { get; set; } //Pri Key
    public string Name { get; set; }

    [ForeignKey("FoodRecipe")] // Personally I prefer using explicit foreign key attributes to avoid implicit jankiness
    public int FoodRecipeID { get; set; }

    [ForeignKey("Ingredient")]
    public int IngredientID { get; set; }

    //Navigation Properties
    public virtual FoodRecipe FoodRecipe { get; set; }


    public virtual Food Ingredient { get; set; }
}

public class FoodRecipe
{
    [Key]
    public int FoodRecipeID { get; set; } //Pri Key
    public string Name { get; set; }
    [ForeignKey("Food")] // Personally I prefer using explicit foreign key attributes to avoid implicit jankiness
    public int FoodID { get; set; }//Foreign Key
    public virtual Food Food { get; set; }
    public virtual ICollection<FoodRecipeEntry> FoodRecipeEntries {get; set; }//Navigation Property
}

推荐阅读