首页 > 解决方案 > 用户更改密钥时保存模型时出错

问题描述

我有一个使用字符串作为键而不是 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.

标签: c#asp.net-mvc-4entity-framework-6

解决方案


此错误可能意味着以下一些事情:

  • 正如错误所暗示的那样,可能是实体已被修改,因为您从数据库中获取它(并发)
  • 您的数据库可能不包含具有该 ID 的实体
  • 可能是您在解决方案中使用了 2 个不同的 DBContext

这些是一些可能的事情。

我想发表评论,但我没有这样做的声誉,所以我直接回答了。


推荐阅读