title: Attaching duplicate existing entities to a new entity
body: <p>I have a projects table which has three associations to the contacts table, one for each type of contact (Sponsor, Broker, Logistics).   I allow a user to select from an existing list of contacts. If the same contact is selected for two or more of these my code gets them correctly pointed to the existing entry, but I get a new unused contact entry in the database.</p>
  
  <p>I only allow the first of any duplicates to be modified, I assemble them detached and then attach to the DbContext prior to saving.</p>
  
  <pre><code>if (newProject.SponsorContact != null &amp;&amp; newProject.SponsorContact.Id &gt; 0)
      if (AttachContact(newProject.SponsorContact))
      SdContext.Entry(newProject.SponsorContact).State = EntityState.Modified;
      else
      newProject.SponsorContact = _contactDataMapper.GetContactById(newProject.SponsorContact.Id);
  
  
  if (newProject.BrokerContact != null &amp;&amp; newProject.BrokerContact.Id &gt; 0)
      if (AttachContact(newProject.BrokerContact))
      SdContext.Entry(newProject.BrokerContact).State = EntityState.Modified;
      else
      newProject.BrokerContact = _contactDataMapper.GetContactById(newProject.BrokerContact.Id);
  
  if (newProject.LogisticsContact != null &amp;&amp; newProject.LogisticsContact.Id &gt; 0)
      if (AttachContact(newProject.LogisticsContact))
      SdContext.Entry(newProject.LogisticsContact).State = EntityState.Modified;
      else
      newProject.LogisticsContact = _contactDataMapper.GetContactById(newProject.LogisticsContact.Id);
  </code></pre>
  
  <p>AttachContact just keeps track of the attached contact id's and returns false if already attached so that I can grab the existing contact from the context. </p>
  
  <pre><code>protected bool AttachContact(Contact contact)
  {
      if (!_attachedContacts.Contains(contact.Id))
      {
      _attachedContacts.Add(contact.Id);
      return true;
      }
      return false;
  }
  </code></pre>
  
  <p>So if I choose Jacob Marley with ContactId 17 twice, my project saves with both entries pointing to the correctly modified Jacob Marley id 17, but I get a new Jacob Marley also saved in the contact table with no project pointing to that entry.   Giving serious consideration to accessing the context during assembly so I know existing entries are already attached.</p>