title: How to insert using many to many relationship with entity framework
body: <p>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:</p>
  
  <pre><code>public class DataContext : DbContext
  {
      public DbSet&lt;Student&gt; StudentsContext { get; set; }
      public DbSet&lt;Group&gt; GroupsContext { get; set; }
      public DbSet&lt;Phase&gt; PhaseContext { get; set; }
      public DbSet&lt;Admin&gt; AdminContext { get; set; }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          base.OnModelCreating(modelBuilder);
          modelBuilder.Entity&lt;Student&gt;()
              .HasMany(g =&gt; g.Groups)
              .WithMany(s =&gt; s.GroupMembers)
              .Map(x =&gt; x.MapLeftKey("StudentId")
                  .MapRightKey("GroupId")
                  .ToTable("Student_XRef_Group"));
  
      }
  }
  </code></pre>
  
  <p>Then in controller just as a test I would try:</p>
  
  <pre><code>        var phase = phaseRepository.Select().SingleOrDefault(x =&gt; 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();
  </code></pre>
  
  <p>Then when it reaches context.savechanges I get the following error:</p>
  
  <p><em>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.</em></p>
  
  <p>** 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?</p>