首页 > 解决方案 > 尝试在实体框架中更新时出现错误“发生参照完整性约束冲突”

问题描述

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

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; }
}

标签: c#asp.net-mvcentity-framework

解决方案


编辑:

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

'违反参照完整性约束'

你需要修复你的数据。


推荐阅读