I am getting the following error message when I try to update my data back to the table:
Attaching an entity of type 'Namespace.Models.Child' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values.
Like usual I am guessing it is something simple but I am not sure where the issue is.
[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);
}