更新子实体时出错

时间:2013-07-12 02:54:48

标签: asp.net-mvc entity-framework

尝试更新模型及其子集合时出现以下错误:

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

要解决此问题,我只需要颠倒这些行的顺序:

UpdateCategories(selectedCategories, form.Manufacturer);
db.Entry(form.Manufacturer).State = EntityState.Modified;

现在:

   db.Entry(form.Manufacturer).State = EntityState.Modified;
   UpdateCategories(selectedCategories, form);