c# - Entity Framework Detached multiple many-to-many Entities -
usually, page have single main entity , have child entities. had solution before type of detached many-to-many
e.g.
db.entry(class).state = entitystate.modified; foreach(var student in class.student) {   var dbstudent = db.students.find(student.studentid);   dbstudent.classes.add(class); }   my problem have multiple classes in view , causing "entity of same type has same primary key value"
e.g. looping list of classes
foreach(var class in viewmodel.classes) {   db.entry(class).state = entitystate.modified; }   above code throw error on reaching 2nd class if same student present in both classes. because assigning entitystate loads child entities , create 2 instances of same student.
i tried manipulate creating temporary collection have single instance
e.g.
var students = new list<students>(); foreach(var class in viewmodel.classes) {   foreach(var student in class.students) {      student dbstudent = null;      if(!students.any(s => s.studentid == student.studentid)) {       dbstudent = db.student.find(student.studentid);       students.add(dbstudent);       db.entry(dbstudent).state = entitystate.modified;     }      else {       dbstudent = students.where(s => s.studentid == student.studentid).singleordefault();     }      dbstudent.classes.add(class);   }   db.entry(class).state = entitystate.modified; }   the code above works new entries, existing entries causes "primary key error" me says detached. not work when trying remove existing entry.
anybody can me here? thanks
 
 
  
Comments
Post a Comment