Search code examples
asp.net-mvc-3entity-framework-5entity-relationship

Update and Create New Records in the Same Table


How can I apply changes to the first record in a table and add one or more additional records to the same table? I am getting the following exception:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

See sample code below.

var Student = db.Student.Where(d => d.StudentID == studentID);
                                        int count = 0;    
                                        if(Student != null)
                                            {
                                                foreach(var student in Student)
                                                {
                                                    if (student.Id == id)
                                                    {
                                                        foreach (var assign in assignment)
                                                        {
                                                            if (assign != null && count == 0)
                                                            {
                                                               //How can I save the changes that is made to the first record here
                                                                assign.AssignmentId = student.AssignmentID;
                                                                db.Assignment.ApplyCurrentValues(assign);
                                                            }

                                                            if (assign != null && count > 0)
                                                            {
                                                                //How can I add new records here
                                                                assign.AssignmentId = student.AssignmentID;
                                                                db.Assignment.AddObject(assign);
                                                            }
                                                            count++;
                                                        }
                                                    }


                                                }
                                            }

Solution

  • Try calling save after this line i.e.

    db.Assignment.ApplyCurrentValues(assign);
    db.SaveChanges();
    

    Then for your new entries:

    var assignment = new Assignement() { AssignmentId = student.AssignmentID };
    db.Assignments.Add(model);
    db.SaveChanges();