我的桌子有这种关系。 Activity
,Workstation
,Platform
,Part
是查找表。
我ActivitWorkstation
包含(ActivityId, WorkstationId)
和Activity
个表的Workstation
个外键。
我还PlatformPart
包含(PlatformId, PartId)
和Platform
表的Part
个外键。
最后,我有PartStaging
表,(ActivityWorkstationId, PlatformPartId)
和ActivityWorkstation
表有PlatformPart
个外键。
以下是我的PartStaging
修改方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PartStagingVM partstagingvm)
{
if (ModelState.IsValid)
{
PartStaging partstaging = new PartStaging();
var activityWorkstation = db.ActivityWorkstations.FirstOrDefault(aw => aw.ActivityId == partstagingvm.ActivityId && aw.WorkstationId == partstagingvm.WorkstationId);
if (activityWorkstation == null)
{
activityWorkstation = new ActivityWorkstation
{
ActivityId = partstagingvm.ActivityId,
WorkstationId = partstagingvm.WorkstationId
};
db.Entry(activityWorkstation).State = EntityState.Added;
}
var platformPart = db.PlatformParts.FirstOrDefault(pp => pp.PlatformId == partstagingvm.PlatformId && pp.PartId == partstagingvm.PartId);
if (platformPart == null)
{
platformPart = new PlatformPart
{
PlatformId = partstagingvm.PlatformId,
PartId = partstagingvm.PartId
};
db.Entry(platformPart).State = EntityState.Added;
}
var partStaging = db.PartStagings.FirstOrDefault(ps => ps.ActivityWorkstationId == activityWorkstation.Id && ps.PlatformPartId == platformPart.Id);
if (partStaging != null && partStaging.Id != partstagingvm.Id)
{
TempData["Message"] = "The record already exists.";
}
else
{
partstaging.Id = partstagingvm.Id;
partstaging.ActivityWorkstationId = activityWorkstation.Id;
partstaging.PlatformPartId = platformPart.Id;
partstaging.Description = partstagingvm.Description;
db.Entry(partstaging).State = EntityState.Modified;
db.SaveChanges();
TempData["Message"] = "The record has been modified.";
}
return RedirectToAction("Edit");
}
return View(partstagingvm);
}
我可以修改ActivityWorkstation
。我可以修改PlatformPart
。当记录已经存在时,它阻止我更新。但是在编辑Description
时我遇到了问题。它应该是最简单的更新,因为我所要做的就是分配:
partstaging.Description = partstagingvm.Description
但是当我提交时,我收到了这个错误:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
Source Error:
Line 216: partstaging.Description = partstagingvm.Description;
Line 217:
Line 218: db.Entry(partstaging).State = EntityState.Modified;
Line 219: db.SaveChanges();
Line 220:
我错过了什么?