有什么方法可以将 class 元素嵌入到 Entity Framework 中的 class 元素中?

Is there any way to embed a class Element into a class Element in Entity Framework?

这是我的代码:

namespace MyProject.Models.Database
{
    public class Recipe
    {
        public Guid Id { get; set; } = Guid.NewGuid();
        public string Name { get; set; }
        public string? Description { get; set; }
        public string? Picture { get; set; }
        public int Worktime { get; set; }
        public int? Cooktime { get; set; }
        public int Difficulty { get; set; }
        public int Portions { get; set; }
        public List<Ingredient> Ingredients { get; set; }
    }
    public class Ingredient
    {
        public Guid Id { get; set; } = Guid.NewGuid();
        public Guid IngredientId { get; set; }
        public int Qty { get; set; }
        public string QtyUnit { get; set; }
    }
}

我希望 class“食谱”包含许多“成分”类型的元素。我读过有关一对一和多对多的内容,但我就是不明白...

有什么想法吗? 谢谢

一个菜谱可以包含多种食材,一种食材也可以出现在很多菜谱中。这是many-to-many关系。

您需要做的是创建一个新的 class,其中包含 IdRecipeIdIngredientId。将 class 命名为 RecipeIngredient。在数据库上下文中创建 DbSet<RecipeIngredient> 时,将 table 命名为 RecipesIngredients.

RecipeIngredient中属性的数据类型应该是什么?

Id属性为主键,数据类型由你决定。

RecipeId 将是 Recipe 的外键,因此它需要与 Recipe 的主键相同的数据类型(在您的情况下 Guid)。

IngredientId 将是 Ingredient 的外键,因此在您的情况下数据类型将再次为 Guid

请注意,您可以创建一个复合键,而不是将 Id 放入 RecipeIngredient。

你应该什么时候做? -> here

我建议您了解不同的关系以及如何使用 C# 和 Entity Framework 核心应用它们 -> here

祝您学习之旅顺利!当你觉得自己不了解某个主题时,不要担心也不要气馁,你只是需要更多的经验。继续努力:)