当我尝试更新实体时出现错误:
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; }
}
答案 0 :(得分:0)
编辑:
Recipe.Id和Ingredient.RecipeId具有不同的值,导致
“违反了参照完整性约束”
您需要修复数据。