I have 2 entities with many-to-many relationship.
public class Student{
public int Id { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
}
public class Subject
{
public int Id { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
this is the definition of many-to-many mapping between two entities,
modelBuilder.Entity<Student>()
.HasMany<Subject>(s => s.Subjects)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.ToTable("SubjectsStudents");
});
All the subjects are predefined and already in the database. Adding subjects to student is straight forward.
In this, I want to add or remove subjects from each student (update relationship between student and existing subjects).I have the list of subject ids the student should be assigned when update.
How can I update subjects list of student?
Update
This is what I tried.
List<Subject> updatedList = //new list that the student should be assinged;
var entity = ctx.Students
.Include(n => n.Subjects)
.Single(n => n.Id == item.Id);
List<Subject> deleteList = //get currently assigned subjects which are not in updatedList;
foreach (Subject subject in deleteList) {
entity.Subjects.Remove(store);
}
foreach (Subject subject in updatedList)
{
ctx.Subjects.Attach(subject);
ctx.Entry(subject).State = EntityState.Unchanged;
}
ctx.Entry(entity).State = EntityState.Modified;
ctx.SaveChanges();
Getting exception: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.