控制器中的ObjectStateManager错误中已存在具有相同键的对象



我的控制器中有以下ActionResults(为简单起见,已截断)。当我发帖时,我得到了一个错误:ObjectStateManager中已经存在一个具有相同键的对象。我想这是因为我正在GET ActionResult:中加载一个实体

var t = iEquipmentTaskRepository.GetSingle(taskID);

然后在帖子中再次加载它,并尝试编辑/保存它。我需要向数据库中添加一个新的维护实体,并更新(现有)EquipmentTask实体中的值。如何在ObjectStateManager中获得对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);
}

我弄清楚了发生了什么。我不需要创建EquipmentTask(Duh)的新实例:

var t = iEquipmentTaskRepository.GetSingle(maintenanceViewModel.TaskId);
EquipmentTask equipmentTask = new EquipmentTask(); // <-- this line was not necessary
equipmentTask.TaskId = maintenanceViewModel.TaskId;
equipmentTask.MaintenanceDueDate = nextDueDate;

我没有添加新实例,只是更新了一个现有实例。一旦我删除了这条线,它就起作用了:

var equipmentTask = iEquipmentTaskRepository.GetSingle(maintenanceViewModel.TaskId);
equipmentTask.TaskId = maintenanceViewModel.TaskId;
equipmentTask.MaintenanceDueDate = maintenanceViewModel.NextDueDate;

相关内容

  • 没有找到相关文章

最新更新