MVC问题更新表(viewModel)映射

时间:2014-12-05 01:50:52

标签: c# asp.net-mvc entity-framework

当我尝试将数据更新回表格时,收到以下错误消息:

附加“Namespace.Models.Child”类型的实体失败,因为同一类型的另一个实体已具有相同的主键值。如果图中的任何实体具有冲突的键值,则在使用“附加”方法或将实体的状态设置为“未更改”或“已修改”时,可能会发生这种情况。

像往常一样,我猜它很简单,但我不确定问题出在哪里。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(ParentsCreateVM viewModel)
    {
        if (ModelState.IsValid)
        {
            var parent = new Parent()
            {
                FirstName = viewModel.FirstName,
                LastName = viewModel.LastName,
                ParentID = viewModel.ParentID
            };

            //db.Parents.Add(parent);
            db.Entry(parent).State = EntityState.Modified;

            foreach (ChildVM item in viewModel.Children)
            {

                var child = new Child()
                {
                    Name = item.Name,
                    DOB = item.DOB,
                    Address = item.Address,
                    ParentID = viewModel.ParentID,
                    ChildID = item.ChildID

                };

                 db.Entry(child).State = child.ChildID == 0 ?
                               EntityState.Added :
                               EntityState.Modified; 

            }



            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(viewModel);
    }

1 个答案:

答案 0 :(得分:0)

异常很明显,dbcontext已经加载了相同的子项。

我建议你这样做

//find child item in db
var child = db.Entry<Child>().Single(child=>child.key== value);
//then chang value
child.Name = item.Name;
child.DOB = item.DOB;
child.Address = item.Address;