0

如何将更改应用到表中的第一条记录并将一个或多个附加记录添加到同一个表?我收到以下异常:

ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象

请参阅下面的示例代码。

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++;
                                                        }
                                                    }


                                                }
                                            }
4

1 回答 1

0

尝试在此行之后调用 save 即

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

然后对于您的新条目:

var assignment = new Assignement() { AssignmentId = student.AssignmentID };
db.Assignments.Add(model);
db.SaveChanges();
于 2013-07-11T14:22:24.220 回答