Sql – “An attempt has been made to Attach or Add an entity that is not new…” after calling ObjectChangeConflict.Resolve()

linq-to-sql

I have a pair of classes which, when updated together as shown below are guaranteed to cause a ChangeConflictException because a trigger on child object table updates a value on the parent object record. I believe I am following the correct procedure for resolving the conflict and resubmitting the update, but upon calling the second db.SubmitChanges (or even if I call db.GetChangeSet()), I get the "an attempt has been made to attach or add an entity that is not new blah blah blah" error.

        using (SurveyDB db = new SurveyDB())
        {
            Parent p = db.Parents.Single(t => t.Id == 1);
            p.Children.Add(new Child {...});
            p.SomeProperty = "new value";
            try
            {
                db.SubmitChanges();
            }
            catch (ChangeConflictException e)
            {
                foreach (ObjectChangeConflict o in db.ChangeConflicts)
                    o.Resolve(RefreshMode.KeepChanges, true);

                db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            }
        }

Any help greatly appreciated.

Best Answer

The resolution for me was to set dbml "Update Check" property for the fields set by the trigger to "Never" - this works for the situation where the application never modifies those fields. Otherwise, I'd have had to call SubmitChanges twice - once after editing the parent object and then again after adding the child object (followed by retrieving the parent-object again).