0

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

4

1 回答 1

1

您正在将具有相同键的两个对象附​​加到相同的上下文:vinrepository.GetVisit(id)visitin repository.UpdateVisit(visit)。这会导致异常。

由于您已经从数据库中加载了实体,您只需更新其属性然后保存即可。而不是使用...

repository.UpdateVisit(visit);

...利用...

repository.UpdateAttachedVisit(v, visit);

...和:

public void UpdateAttachedVisit(Visit attachedVisit, Visit detachedVisit)
{
    entities.Entry(attachedVisit).CurrentValues.SetValues(detachedVisit);
}
于 2012-04-29T21:56:49.243 回答