我正在尝试在我的 ASP.NET MVC 应用程序中添加功能来更改我的数据结构的某些字段。单击表单上的提交按钮后,将调用以下操作:
[HttpPost]
public ActionResult Edit(Document doc)
{
// Attempt to save the project
if (_documentService.SaveDocument(doc) == ServiceActionResult.Success)
return RedirectToAction("List");
else
return View();
}
该SaveDocument()
方法如下所示:
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;
}
由于文档存在(因此具有 Id 值),我调用Attach()
通用存储库的方法。附加方法看起来像:
public void Attach(T entity)
{
_objectSet.Attach(entity);
}
调用对象集的Attach()
方法时,会出现以下异常:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
我不明白为什么会发生这种情况,因为正如您所见,请求的整个生命周期只有一次对 EF 的调用,这就是最后一次Attach(entity)
调用。我错过了什么吗?
作为一个仅供参考,这个系统曾经可以工作,但似乎打破它的是我使用 POCO(最新的 CTP)从模型优先到代码优先的转换。我的所有其他功能都像以前一样工作,除了这种情况。
如果有帮助,我的通用存储库会ObjectSet
通过DbContext
我在上下文类中编写的函数获取:
public ObjectSet<T> CreateObjectSet<T>() where T : class
{
return ObjectContext.CreateObjectSet<T>();
}
编辑: 由于评论查看了我的代码后,我才记得我已经实现了一个用于上下文管理的单例。我这样做是因为控制器可能从一个服务类中获取实体,并使用另一个服务类来更新它(我认为这是我试图解决的场景,我不久前实现了它,我'我下班时必须仔细观察)。
我为此使用了单例,因为我的印象是单例不会跨越多个 http 请求,并且我认为这可能是问题所在。我回家时会看看这个。