实体框架更新实体错误
本文关键字:实体 错误 框架 更新 | 更新日期: 2023-09-27 18:25:10
我得到了一个通用错误:-
附加信息:附加"entity"类型的实体失败因为同一类型的另一个实体已经具有相同的主实体键值。使用"Attach"方法或设置时可能会发生这种情况如果中的任何实体该图具有冲突的键值。这可能是因为实体是新的,尚未收到数据库生成的密钥价值观在这种情况下,请使用"Add"方法或"Added"实体状态以跟踪图形,然后将非新实体的状态设置为"未更改"或"修改"(视情况而定)
当实体试图更改其状态时,它发生在下面的行上。
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;
}
}
然而,当我时,我得到了它
- 重新加载上下文,即从视图初始化存储库
- 正确使用attach而不是
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 });
}
上面的代码出现这个错误是有原因的吗?
感谢
您已经在代码的注释中发现了问题:
// 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字段。