title: Adding an existing entity to a child collection of a many-to-many relationship
body: <p>I have to entities that represent a <code>Message</code> and a <code>Topic</code>.<br>
  A <code>Message</code> can have many <code>Topic</code>, and a <code>Topic</code> can belong to many <code>Message</code></p>
  
  <pre><code>public class Message
  {
      [Key]
      public int Id { get; set; }
  
      public string Text { get; set; }
  
      public virtual ICollection&lt;Message&gt; Topics { get; set; }
  }
  
  public class Topic
  {
      public int Id { get; set; }
  
      public string Value { get; set; }
  
      public virtual ICollection&lt;Message&gt; Messages { get; set; }
  }
  </code></pre>
  
  <p>In my application, we first save <code>Topic</code> (early on in the application, sometimes seed data etc...)</p>
  
  <p>Later, I need to save a new <code>Message</code> - adding an already existing <code>Topic</code> to the child collection;</p>
  
  <pre><code>var message = new Message();
  message.Text = "Hello";
  //this topic already exists in the database
  message.Topics.Add(new Topic{Id = 6, Value = "val"}); 
  dbContext.Messages.Add(message);
  dbContext.SaveChanges();
  </code></pre>
  
  <p>What happens is:  </p>
  
  <ul>
  <li><code>Message</code> is saved</li>
  <li><em>New</em> topic is created (with Value of "val")</li>
  <li>ID of <em>new</em> topic is saved in MessageTopics mapping table against the newly created <code>Message</code> ID</li>
  </ul>
  
  <p>What I want to happen is</p>
  
  <ul>
  <li><code>Message</code> is saved</li>
  <li>ID of supplied topic (6 in this case) is saved in MessageTopics table against the newly created <code>Message</code> ID</li>
  </ul>