如何更新模型 class 配方?

how to update the model class recipe?

我有两个模型 类 Category 和 Recipe 以及它们之间的一对多关系。我想编辑菜谱,还要提前更改菜谱所属的类别to.Thanks。

    public class CookContext : DbContext 
    {
        public CookContext(): base("cookContext")
        {

        }

        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<Category> Categories { get; set; }
   }
     public class Category
     {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Recipe> Recipes { get; set; }
     }

     public class Recipe
     {

         public int Id { get; set; }
         [Required]
         public string Title { get; set; }
         [Required]
         public string Description { get; set; }
         [Required]
         public string Ingridients { get; set; }

         public string Image { get; set; }

         public Category category { get; set; }
     }

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult EditRecipe(Recipe recipe, int? categoryName)
    {
        var category = context.Categories.Where(c => c.Id == 
        (int)categoryName).FirstOrDefault();
        context.Entry(recipe).State = EntityState.Modified;
        recipe.category = category;
        context.SaveChanges();
    }

我收到的错误信息是: 1. [DbUpdateException:保存不为其关系公开外键属性的实体时发生错误。 EntityEntries 属性 将 return 为空,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地处理保存时的异常。 2. 存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。有关理解和处理乐观并发异常的信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=472540

尝试将字段 CategoryId 添加到您的 Recipe class,此外,category 属性 应该以大写开头 "C".

如果您希望延迟加载数据(仅在需要时加载),则应将集合 属性 标记为虚拟,否则,您可能会在每次查询时加载给定类别的所有食谱:

public class Recipe
{
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public string Ingridients { get; set; }

    public string Image { get; set; }

    public int CategoryId { get; set; }

    public Category Category { get; set; }
}

public class Category
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Recipe> Recipes { get; set; }
}

如果它不起作用,请尝试设置 ForeignKey 属性:

public class Recipe
{

    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public string Ingredients { get; set; }

    public string Image { get; set; }

    [ForeignKey("Category")]
    public int CategoryId { get; set; }

    public Category Category { get; set; }
}

public class Category
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Recipe> Recipes { get; set; }
}