首页 文章

实体框架6.1.3;代码首次迁移多对多连接表

提问于
浏览
0

我使用VS项目中的代码优先迁移生成了一个localDB . 我在两个实体( RecipeIngredient )之间存在多对多关系 .

我的模型类:

public class Recipe
{
    [Key]
    public int RecipeId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Ingredient> Ingredients { get; set; }  
}

public class Ingredient
{
    [Key]
    public int IngredientId { get; set; }
    [Required]
    public string Name { get; set; }
    public bool Organic { get; set; }
    public bool Vegan { get; set; }
    public virtual ICollection<Recipe> Recipes { get; set; } 

}

我用EF生成的模式结果如下:

Table Overview

一个名为 RecipeIngredients 的连接表包含两个外键( RecipeIdIngredientId ),这就是我所追求的,但......

Problem: 我想在 RecipeIngredient 表中有一个额外的列( Quantity ) . 我该如何解决这个问题?

1 回答

  • 0

    无法向Entity Framework自动生成的连接表添加任何其他列 .

    您应该创建一个包含所需信息的新实体 RecipeIngredient ,并在 RecipeIngredientIngredient 之间定义一对多关系,在 RecipeIngredientIngredient 之间定义另一个关系 .

    public class Recipe {
        [Key]
        public int RecipeId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public virtual ICollection<RecipeIngredient> Ingredients { get; set; }  
    }
    
    public class Ingredient {
        [Key]
        public int IngredientId { get; set; }
        [Required]
        public string Name { get; set; }
        public bool Organic { get; set; }
        public bool Vegan { get; set; }
        public virtual ICollection<RecipeIngredient> Recipes { get; set; } 
    }
    
    public class RecipeIngredient {
        [Key, Column(Order = 0)]
        public int RecipeID { get; set; }
        [Key, Column(Order = 1)]
        public int IngredientID { get; set; }
        public double Quantity { get; set; }
    }
    

相关问题