title: Entity Framework duplicate entries in many to many relationship
body: <p>I have already read many posts about the entity framework problem with many to many and its beeing a pain in the neck again.</p>
  
  <p>Colaborador has an ICollection of Time and
  Time has an Icollection of Colaborador</p>
  
  <p>Some people say that it´s necessary to attach the child entity before Add in the context(didn´t work for me, Pk error).</p>
  
  <p>I am using simple injector and my context is per request.</p>
  
  <p>My associative table is mapped like this:</p>
  
  <pre><code>            HasMany&lt;Time&gt;(c =&gt; c.Times)
              .WithMany(t =&gt; t.Colaboradores)
              .Map(ct =&gt;
              {
                  ct.MapLeftKey("ColaboradorId");
                  ct.MapRightKey("TimeId");
                  ct.ToTable("Receptor");
              });
  </code></pre>
  
  <p>It creates the associative table in the database.
  When i try to insert a Colaborador(entity), i add in its list some Times(Teams), add to DbContext and then SaveChanges().</p>
  
  <p>When i do this, it creates a new Colaborador, insert correctly in the associative table(the ids) but also duplicate the Time.</p>
  
  <pre><code>var colaborador = Mapper.Map&lt;ColaboradorViewModel, Colaborador&gt;(colaboradorVm);
  List&lt;TimeViewModel&gt; timesVm = new List&lt;TimeViewModel&gt;();
  colaboradorVm.TimesSelecionados.ForEach(t =&gt; timesVm.Add(_serviceTime.BuscarPorId(t)));
  
  colaborador.Times = Mapper.Map&lt;ICollection&lt;TimeViewModel&gt;, ICollection&lt;Time&gt;&gt;(timesVm); 
  </code></pre>
  
  <p>The function BuscarPorId does the Find method and returns a Time.</p>
  
  <p>I have figured out that if i call the Add command, the entity will mark the child´s state as Added as well, but if i attempt to attach the Time or change it´s state to Unchanged, i get a primary key error...</p>
  
  <pre><code>foreach (var item in colaborador.Times)
  {                
      lpcContext.Set&lt;Time&gt;().Attach(item);
      //lpcContext.Entry(item).State = EntityState.Unchanged;
  }
  </code></pre>
  
  <p>Is there any way of tell to entity framework to not insert a specific child? So only the main and associative table are populated?</p>