I am trying to add functionality in my ASP.NET MVC application to change some fields of my data structure. After clicking the submit button on the form, the following action is called:
[HttpPost]
public ActionResult Edit(Document doc)
{
if (_documentService.SaveDocument(doc) == ServiceActionResult.Success)
return RedirectToAction("List");
else
return View();
}
The method is SaveDocument()as follows:
public ServiceActionResult SaveDocument(Document doc)
{
if (doc == null)
return ServiceActionResult.ActionFailure;
// Check if this is a new Document (null ID)
if (doc.Id == 0)
_documentRepository.Add(doc);
else
_documentRepository.Attach(doc);
_documentRepository.SaveChanges();
return ServiceActionResult.Success;
}
Since the document exists (and therefore has an Id value), I call the method of Attach()my shared repository. The attach method is as follows:
public void Attach(T entity)
{
_objectSet.Attach(entity);
}
When calling the method of the object Attach(), the following exception occurs:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I don’t understand why this is happening, because since you can see that the entire request life cycle has only one EF call, and that last call Attach(entity). Did I miss something?
Like FYI, this system was used to work, but it seems to have broken, it was my conversion from the model first, to first encode POCOs (last CTP). All my other functions work the same as before, except for this scenario.
If this helps, my shared repository gets ObjectSetfrom DbContextthrough a function that I wrote in my context class:
public ObjectSet<T> CreateObjectSet<T>() where T : class
{
return ObjectContext.CreateObjectSet<T>();
}
Edit
After reviewing my code due to comments, I just remembered that I implemented a singleton to control the context. I did this because it is possible that the controller can get objects from one service class and use another service class to update it (I think it was a script that I was trying to solve, I implemented it some time ago, d should look closer when I get off work)., , HTTP-, , . , .