尝试更新模型及其子集合时出现以下错误:
ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。
[HttpPost]
public ActionResult Edit(ManufacturerViewModel form, string[] selectedCategories)
{
if (ModelState.IsValid)
{
UpdateCategories(selectedCategories, form.Manufacturer);
//TODO: Handle links relationship
db.Entry(form.Manufacturer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
private void UpdateCategories(string[] selectedCategories, Manufacturer mfr)
{
var categoryIds = selectedCategories.Select(c => int.Parse(c)).ToList();
foreach (var category in GetCategories())
{
if (categoryIds.Contains(category.ID))
{
if (!mfr.Categories.Contains(category))
mfr.Categories.Add(category);
}
else
{
if (mfr.Categories.Contains(category))
mfr.Categories.Remove(category);
}
}
}