c# - 尝试在实体框架中更新时出现错误“发生参照完整性约束冲突”
问题描述
当我尝试更新实体时出现错误:
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; }
}
解决方案
编辑:
Recipe.Id 和 Ingredient.RecipeId 具有不同的值,这会导致
'违反参照完整性约束'
你需要修复你的数据。
推荐阅读
- javascript - 如何onClick将文本从a复制到剪贴板
使用 JavaScript/jQuery 标记?
- typescript - 如何在 TypeScript 的 Koa 调试模式下将自定义中间件函数记录到控制台?
- javascript - 来自 XMLHttpRequest 文本的 JS ArrayBuffer
- excel - 库存宏 - 结合步骤和while循环?
- node.js - Firebase 部署在 tsc 命令返回错误
- kubernetes - Kubernetes Ingress:为什么我在相同的配置下得到不同的结果,但不同的主机?
- java - 如何解决我的代码中的 java.lang.NumberFormatException: Invalid int: "" 错误?
- python - 从 def __init__() 访问 def clean() 中的变量
- javascript - JavaScript 检查是否在 HTML 表单中选择了多个单选输入中的任何一个
- jquery - jQuery 解析 xml 无效的 XML:HTTP/1.1 200 OK