【问题标题】:Entity Framework Updating Entities error实体框架更新实体错误
【发布时间】:2025-12-14 22:30:01
【问题描述】:

我得到了一个一般性错误:-

附加信息:附加“实体”类型的实体失败 因为另一个相同类型的实体已经有相同的主 核心价值。使用“附加”方法或设置时可能会发生这种情况 实体的状态为“未更改”或“已修改”,如果存在 该图具有冲突的键值。这可能是因为一些 实体是新的,尚未收到数据库生成的密钥 价值观。在这种情况下,使用“添加”方法或“添加”实体状态 跟踪图,然后将非新实体的状态设置为 “未更改”或“已修改”(视情况而定)

当实体试图改变其状态时,它发生在线下方。

public void InsertOrUpdate(T entity)
    {
        if (entity.Id == default(int))
        {
            entity.Created = DateTime.Now;
            entity.LastEdit = DateTime.Now;

            Context.Initial.Add(initial);
        }
        else
        {
            entity.LastEdit = DateTime.Now;
            Context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
        }
    }

但是,当我得到它时

  • 重新加载上下文,即从视图初始化存储库。
  • 正确使用附件Context.T.Attach(entity)

当我不更改状态信息或使用附加时,它不会更新任何内容。

这是我的控制器代码

[HttpPost]
[Authorize]
public ActionResult Create(NewViewModel viewModel)
{
   if (ModelState.IsValid)
   {
      m_CTS.InsertOrUpdate(viewModel.entity);
      m_CTS.Save();

      // My big problem is that the Primary key that 
      // was generated doesnt come back from the view 
      // once edited, so I have created a property in 
      // the viewmodel to handle this

      viewModel.ID = viewModel.entity.Id;

      return RedirectToAction("Edit", new { id = viewModel.entity.Id });
    }
    else
    {
      return View("New", viewModel);
    }
}

[HttpGet]
[Authorize]
public ViewResult Edit(int id)
{
  // Getting this from the same context of when it was created
  viewModel.entity = respoitory.Find(id);

  return View(viewModel);
}

[HttpPost]
[Authorize]
public ActionResult Edit(NewViewModel viewModel)
{
   // Could be the problem : As I said above the ID on the entity.id 
   // never comes back from the view (because I am using a viewmodel?) 
   // So I need to assign the ViewModel ID to the entity model id 
   // before I try and update it

   viewModel.entity.Id = viewModel.ID;

   m_CTS.InsertOrUpdate(viewModel.entity);
   m_CTS.Save();

   return RedirectToAction("Edit", new { id = viewModel.entity.Id });
}

上面的代码出现这个错误是有原因的吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    您已经在代码的 cmets 中发现了问题:

           // My big problem is that the Primary key that 
           // was generated doesnt come back from the view 
           // once edited, so I have created a property in the viewmodel to handle this
    

    要解决此问题,请将@Html.HiddenFor(m => m.Id) 添加到您的视图中。现在,当您 POST 到控制器时,您的视图模型参数将包含您首先发送到视图的 Id 字段。

    【讨论】:

    • 谢谢,我仍然收到同样的错误,现在返回 POST,谢谢..
    • 那么我不明白这个问题。哪个控制器方法导致异常?
    • 我找到了一个解决方案,当我第一次从上下文中检索实体时,我使用了 AsNoTracking(),不确定这是否是绝对正确的解决方案,到目前为止似乎还可以,当我完成测试时,将发布。欢呼
    • 如果我从您的评论中正确推断出您的设计,DbContext 在 Web 请求之间保持活跃。这准确吗?
    • 是的,这是正确的,我不处理上下文