0

モデルとその子コレクションを更新しようとすると、次のエラーが発生します。

同じキーを持つオブジェクトが 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);
        }
    }
}
4

1 に答える 1