尝试在Entity Framework中进行更新时出现错误“发生了引用完整性约束冲突”

时间:2018-12-20 20:32:58

标签: c# asp.net-mvc entity-framework

当我尝试更新实体时出现错误:

  

System.InvalidOperationException:发生了引用完整性约束冲突:关系一端的'Recipe.Id'的属性值与该关系的'Ingredient.RecipeId'的属性值不匹配另一端。

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RecipeEditViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return View(viewModel);
    }

    var recipe = new Recipe()
    {
        Id = viewModel.Id,
        Name = viewModel.Name,
        AboutDish = viewModel.AboutDish,
        Ingredients = viewModel.Ingredients,
        Directions = viewModel.Directions
    };

    if (viewModel.File != null)
    {
        // upload file logic   
    }

    _context.Entry(recipe).State = EntityState.Modified; //**Error here**
    _context.SaveChanges();

    return RedirectToAction("Index", "Home");
}

模型类:

//recipe.cs
public class Recipe
{
    public int Id { get; set; }

    // Name, etc

    [Required]
    public virtual ICollection<Ingredient> Ingredients { get; set; }
}

// ingredient.cs
public class Ingredient
{
    public int Id { get; set; }

    // Name, etc...

    public int RecipeId { get; set; }

    [ForeignKey(nameof(RecipeId))]
    public virtual Recipe Recipe { get; set; }
}

查看模型:

// RecipeEditViewModel.cs
public class RecipeEditViewModel
{
    public int Id { get; set; }

    // Name, etc...

    public ICollection<Ingredient> Ingredients { get; set; }
}

1 个答案:

答案 0 :(得分:0)

编辑:

Recipe.Id和Ingredient.RecipeId具有不同的值,导致

  

“违反了参照完整性约束”

您需要修复数据。