我有以下EdiePOST操作方法: -
[HttpPost]
public ActionResult Edit([Bind(Include = "Note,DoctorID,VisitID,StatusID,timestamp")] Visit visit) //[Bind(Include="Note,DoctorID,VisitID,StatusID")]
{
if ((visit.EditableByAssingedDoctor(User.Identity.Name)) || (visit.EditableByCreatedBy(User.Identity.Name)))
{
try
{
if (ModelState.IsValid)
{
int id = visit.VisitID;
var v = repository.GetVisit(id);
visit.CreatedBy = v.CreatedBy;
visit.Date = v.Date;
visit.PatientID = v.PatientID;
visit.VisitTypeID = v.VisitTypeID;
repository.UpdateVisit(visit);
repository.Save();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
//code goes here
repository.UpdateVisit(visit);
所在的位置: -
public void UpdateVisit(Visit v)
{
entities.Entry(v).State = EntityState.Modified;
}
但是当我运行我的应用程序并尝试编辑访问对象时,我收到以下错误: -
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
在repository.UpdateVisit(visit);
方法上,那么出了什么问题?
BR
答案 0 :(得分:1)
您将具有相同键的两个对象附加到同一上下文:v
中的repository.GetVisit(id)
和visit
中的repository.UpdateVisit(visit)
。这会导致异常。
由于您已经从数据库加载了实体,因此您只需更新其属性然后保存即可。而不是使用......
repository.UpdateVisit(visit);
... ...使用
repository.UpdateAttachedVisit(v, visit);
...与:
public void UpdateAttachedVisit(Visit attachedVisit, Visit detachedVisit)
{
entities.Entry(attachedVisit).CurrentValues.SetValues(detachedVisit);
}