[英]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
}
这里有一些提示:
FoodRecipeEntry
中删除食物 ID,由于食谱是针对特定食物的,因此食谱隐含了 FoodID,并且该条目属于给定的食谱在代码中,这看起来像这样:
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.