title: EF Code first - Adding many-to-many record, nothing is being saved
body: <p>I'm using EF 4.3 code-first. I have a many-to-many relationship. I am trying in code to attach and save my related records from an array of ids. Ideally I don't want to load those related entities before I save them...</p>
  
  <p>Here is my model - Installers can have many MasterInstances:</p>
  
  <pre><code>public class MasterInstance
  {
      public int MasterInstanceId { get; set; }
      [Required] public string HostName { get; set; }
      [Required] public string Name { get; set; }
      [Required] public string ConnectionString { get; set; }
      public virtual ICollection&lt;MasterInstanceLocation&gt; MasterInstanceLocations { get; set; }
      public ICollection&lt;Installer&gt; PermittedInstallers { get; set; }
  }
  
  public class Installer
  {
      public int InstallerId { get; set; }
      [Required] public string UserName { get; set; }
      [Required] public string Password { get; set; }
      public ICollection&lt;MasterInstance&gt; PermittedMasterInstances { get; set; }
  }
  </code></pre>
  
  <p>In my code, I am trying to attach the <code>master instances</code> to the <code>installer</code> :</p>
  
  <pre><code>installer.PermittedMasterInstances = new List&lt;MasterInstance&gt;();
  foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances)
  {
      var masterInstance = new MasterInstance {MasterInstanceId = permittedMasterInstanceId};
      context.MasterInstances.Attach(masterInstance);
      installer.PermittedMasterInstances.Add(masterInstance);
  }
  
  context.Entry(installer).State = EntityState.Modified;
  context.SaveChanges();
  </code></pre>
  
  <p>But.. Nothing is being written to the link table :( Any ideas why?</p>
  
  <p>EDIT</p>
  
  <p>The only thing that works is this rather unpleasant solution... Is this the only way?</p>
  
  <pre><code>foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances)
  {
      var masterInstance = context.MasterInstances.Single(mi =&gt; mi.MasterInstanceId == permittedMasterInstanceId);
      masterInstance.PermittedInstallers = new List&lt;Installer&gt;();
      context.MasterInstances.Attach(masterInstance);
      masterInstance.PermittedInstallers.Add(installer);
      installer.PermittedMasterInstances.Add(masterInstance);
  }
  </code></pre>