我的控制器中有以下 ActionResults(为简单起见已截断)。当我发布时,我收到错误消息:ObjectStateManager 中已存在具有相同键的对象。我认为这是因为我在 GET ActionResult 中加载了一个实体:
var t = iEquipmentTaskRepository.GetSingle(taskID);
然后在帖子中再次加载它并尝试编辑/保存它。我需要向数据库添加一个新的维护实体并更新(现有)设备任务实体中的值。如何在 ObjectStateManager 中获得对 EquipmentTask 的引用?或者,将 EquipmentTask 实体作为属性添加到我的 MaintenanceViewModel 中会更好吗?我只想更新 EquipmentTask 实体中的一个属性/列
// GET
public ActionResult Create(int taskID = 0)
{
if (taskID == 0)
{
return RedirectToAction("SelectEquipmentTask", "Maintenance");
}
else
{
var t = iEquipmentTaskRepository.GetSingle(taskID);
var maintenanceViewModel = new MaintenanceViewModel
{
DueDate = t.MaintenanceDueDate
};
return View(maintenanceViewModel);
}
}
// POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MaintenanceViewModel maintenanceViewModel)
{
if (maintenanceViewModel.DueDate != null)
nextDueDate = maintenanceViewModel.DueDate.AddDays(7);
Maintenance maintenance = new Maintenance();
maintenance.RowId = maintenanceViewModel.RowId;
// this appears to be my problem. I am loading the same EquipmentTask as the GET method does
var t = iEquipmentTaskRepository.GetSingle(maintenanceViewModel.TaskId);
EquipmentTask equipmentTask = new EquipmentTask();
equipmentTask.TaskId = maintenanceViewModel.TaskId;
equipmentTask.MaintenanceDueDate = nextDueDate;
try
{
if (ModelState.IsValid)
{
iMaintenanceyRepository.Add(maintenance);
iMaintenanceyRepository.Save();
iEquipmentTaskRepository.Edit(equipmentTask);
iEquipmentTaskRepository.Save();
// redirect to the Details view
return RedirectToAction("Details", "Maintenance", new { id = maintenance.RowId });
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
return View(maintenanceViewModel);
}