0

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);
    }
Hockey_Fan
  • 99
  • 10
  • Not sure, but from your previous questions, `Child` has a property `ParentID` which you are not setting –  Dec 05 '14 at 02:14
  • I just added ParentID to the Child in the Edit() Post. I still get the same error. If I can get this to work I will have my CRUD working for all my viewModels. – Hockey_Fan Dec 05 '14 at 02:22
  • Are you editing an existing child or adding a new one? –  Dec 05 '14 at 02:24
  • Editing an existing. Actually, even if I do not edit one, when I submit my edit form I get this error. – Hockey_Fan Dec 05 '14 at 02:25
  • 1
    Then you will also need to set the `ChildID` property (if your doing `db.Childs.Add(child);` in a loop, you keep adding `Childs` whose `ChildID` will be `zero`. Note you can also get the original from the database and just update its properties from the view model –  Dec 05 '14 at 02:28
  • I'm probably confused here, but I'm not inserting I am updating. db.Entry(child).State = EntityState.Modified; – Hockey_Fan Dec 05 '14 at 02:30
  • Yes, but the `ChildID` property of each child your updating has `ChildID=0` –  Dec 05 '14 at 02:32
  • even you mention db.Entry(child).State = EntityState.Modified; but db.Childs.Add(child) mean you add new record, when you add new records, if same key's constraint will give you errors. your EntityState level have to go down one more level, mean every records in the Child model have to tell their own State. – Harris Yer Dec 05 '14 at 02:34
  • @Stephen, I ran the debugger and you are right ChildID is 0 as well as ParentID is 0 for all children. Also the Parent class in the debugger show Childs = null. Do you have any idea what I am doing wrong? – Hockey_Fan Dec 07 '14 at 21:21
  • Are you rendering a control in the view for `ChildID`? And you should set the `ParentID` from the parent, not the child - i.e. `ParentID = viewModel.ParentID` (the `ChildVM` property does not need to include a property for `ParentID`) –  Dec 07 '14 at 21:26
  • I forgot to mention, the code above is the latest, so yes I have the ParentID = viewModel.ParentID in the parent. I also have it in the child but regardless if it is there or not it does not work. What do you mean rendering a control for ChildID? I am using an editor template if that is what you mean. – Hockey_Fan Dec 07 '14 at 21:48
  • No, I mean in `foreach (ChildVM item in viewModel.Children)` it should be `ParentID = viewModel.ParentID` (no need to duplicate controls for `ParentID` in both the `ParentVM` and again in the `ChildVM`. Does you `EditorTemplate` for `ChildVM` include `@Html.HiddenFor(m => m.ChildID)`? –  Dec 07 '14 at 22:24
  • This indicates that your context lives too long, not one context per request. – Gert Arnold Dec 07 '14 at 22:48
  • @Gert, I am not sure I follow you? – Hockey_Fan Dec 07 '14 at 23:10
  • @Stephen, that solved my issue. I added the ParentID = viewModel.ParentID like you requested and I removed the comments from the @Html.HiddenFor(m => m.ChildID) in the Editor Template and I am now in business. Thanks so much. Please post answer so I can give you credit for. – Hockey_Fan Dec 07 '14 at 23:12
  • You have edited you question with the correct code, so giving you an answer wont make much sense now :) –  Dec 07 '14 at 23:20
  • Ooops, my bad. :-( Well, I will know for next time not to modify the answer and follow the proper procedure. Thanks again for your help. – Hockey_Fan Dec 07 '14 at 23:24
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:29

1 Answers1

0

Exception is clear, dbcontext already has load the same child item.

I suggest you do this way

//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;
feiyun0112
  • 761
  • 5
  • 7