我正在尝试在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);
}
当对象集
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Attach(entity)
ObjectSet
DbContext
public ObjectSet<T> CreateObjectSet<T>() where T : class
{
return ObjectContext.CreateObjectSet<T>();
}