ObjectStateManager中已存在具有相同键的对象。 ObjectStateManager无法使用相同的键跟踪多个对象

时间:2012-04-29 19:36:37

标签: asp.net-mvc-3 entity-framework

我有以下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

1 个答案:

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