实体框架更新实体错误

时间:2014-10-01 14:21:26

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

我得到的是一般错误: -

  

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

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

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 });
}

我是否有上述代码出现此错误的原因?

由于

1 个答案:

答案 0 :(得分:1)

您已在代码的注释中发现了问题:

       // 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字段。