简体   繁体   中英

Error “A referential integrity constraint violation occurred” when trying update in Entity Framework

When I'm trying to update entity I'm getting an error:

System.InvalidOperationException: 'A referential integrity constraint violation occurred: The property value(s) of 'Recipe.Id' on one end of a relationship do not match the property value(s) of 'Ingredient.RecipeId' on the other end.'

Controller:

[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");
}

Model classes:

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

View model:

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

    // Name, etc...

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

Edit:

Recipe.Id and Ingredient.RecipeId has different values which causes

'A referential integrity constraint violation"

you need to fix your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM