Reputation: 1
i have the following EdiePOST action method:-
[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
where the repository.UpdateVisit(visit);
is :-
public void UpdateVisit(Visit v)
{
entities.Entry(v).State = EntityState.Modified;
}
But when i run my application and i try to edit the visit object i got the following error :-
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
on the repository.UpdateVisit(visit);
method,, so what are going wrong?
BR
Upvotes: 0
Views: 1208
Reputation: 177153
You are attaching two objects with the same key to the same context: v
in repository.GetVisit(id)
and visit
in repository.UpdateVisit(visit)
. This causes the exception.
Since you already load the entity from the database you can just update its properties and then save it. Instead of using...
repository.UpdateVisit(visit);
...use...
repository.UpdateAttachedVisit(v, visit);
...with:
public void UpdateAttachedVisit(Visit attachedVisit, Visit detachedVisit)
{
entities.Entry(attachedVisit).CurrentValues.SetValues(detachedVisit);
}
Upvotes: 1