c# - 用户更改密钥时保存模型时出错
问题描述
我有一个使用字符串作为键而不是 Id 的模型。
public class Item
{
[Key]
public string SerialNo { get; set; }
但是,我在保存时遇到问题:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Item model)
{
if (ModelState.IsValid)
{
_db.Entry(model).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
更新记录和更改 SerialNo 值时出现错误:
Store update, insert, or delete statement affected an unexpected number of rows... Entities may have been modified or deleted since entities were loaded.
解决方案
此错误可能意味着以下一些事情:
- 正如错误所暗示的那样,可能是实体已被修改,因为您从数据库中获取它(并发)
- 您的数据库可能不包含具有该 ID 的实体
- 可能是您在解决方案中使用了 2 个不同的 DBContext
这些是一些可能的事情。
我想发表评论,但我没有这样做的声誉,所以我直接回答了。
推荐阅读
- angular - RxJs 条件去抖动和采样
- sql - How to calculate time difference between rows
- java - 如何计算饼图中显示的日期与当前日期之间的差异
- rust - 为什么我不能通过`use`导入`std :: assert`,而它适用于std中的其他宏?
- javascript - 如何计算圆形路径上的点?(中心已知)
- javascript - 将 Javascript 变量值发送到电子邮件
- angular - Handsontable numbro 库中的错误,仅在生产版本中发生
- scala - 需要帮助以了解我测试功能的方式是否正确
- java - 如何修复 Android Studio 上的 java.lang.RuntimeException?
- javascript - 通过android(webview)访问javascript变量