簡體   English   中英

關系數據庫:數據庫結構/流程

[英]Relational Databases: Database Structure / Flow

我正在使用實體框架來設置數據庫。 我是關系數據庫的新手,我正在嘗試確定設置幾個表及其關系的正確方法。 這是獨家新聞。

假設我的數據庫中有三個表。

主表是表 A,它包含一個 object 的數據集,我們稱之為 object Food 列: FoodID (主鍵)、RecipeID(與表 C 中的食譜配對的外鍵)。

表 C:包含用於制作存儲在表 A 中的不同Food項目的食譜記錄。列:RecipeID(主鍵)和食譜名稱。

表 B:是用於創建Food的說明/食譜條目。 列:EntryID(主鍵)、RecipeID(外鍵引用表 C 中的食譜 ID)、FoodID(外鍵引用表 A 中的食物)。

我無法圍繞正確的方法來做這件事,因為它是一種循環關系。

我只是從Food表中刪除外鍵( RecipeID )嗎? 在這種情況下,我應該追求的正確流程是什么。

 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; }
}

實體框架 Model 將如下所示。

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
}

這里有一些提示:

  1. FoodRecipeEntry中刪除食物 ID,由於食譜是針對特定食物的,因此食譜隱含了 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM