在同一个表中更新和创建新记录

时间:2013-07-11 13:41:56

标签: asp.net-mvc-3 entity-framework-5 entity-relationship

如何将更改应用于表中的第一条记录,并将一条或多条附加记录添加到同一个表中?我得到以下例外:

  

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


                                                }
                                            }

1 个答案:

答案 0 :(得分:0)

尝试在此行之后调用save,即

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

然后为您的新条目:

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