I'm trying to set up an many to many relationship with groups and students, so students can be assigned to many groups and groups can have many students assigned to it. I keep getting an error when I go to call context.savechanges(). In my objects I do have proper configuration, virtual ICollection in both. My configuration is as follows:
public class DataContext : DbContext
{
public DbSet<Student> StudentsContext { get; set; }
public DbSet<Group> GroupsContext { get; set; }
public DbSet<Phase> PhaseContext { get; set; }
public DbSet<Admin> AdminContext { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Student>()
.HasMany(g => g.Groups)
.WithMany(s => s.GroupMembers)
.Map(x => x.MapLeftKey("StudentId")
.MapRightKey("GroupId")
.ToTable("Student_XRef_Group"));
}
}
Then in controller just as a test I would try:
var phase = phaseRepository.Select().SingleOrDefault(x => x.PhaseId == phaseId);
phase.Groups.Clear();
//Testing
Group testGroup = new Group();
testGroup.GroupNumber = 1;
testGroup.GroupMembers.Add(AllStudents[0]); //Students of type Student
phase.Groups.Add(testGroup);
//Testing
context.SaveChanges();
Then when it reaches context.savechanges I get the following error:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
** SOLVED ** Turns out that by me calling phase.Groups.clear() was the problem, why I do not know. I was hoping maybe can now tell me why?