【问题标题】:Error Updating Child Entities更新子实体时出错
【发布时间】:2013-07-15 03:06:26
【问题描述】:

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

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

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

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

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

    现在是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-13
      • 2018-02-11
      • 1970-01-01
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多