title: Violation of PRIMARY KEY constraint in Entity Framework code first link table
body: <p>I have a User table and a Roles table. There is a automatically generated UsersRoles link table which contains the Id from the User and Roles tables. This is generated using the following code:</p>
  
  <pre><code>modelBuilder.Entity&lt;User&gt;()
                  .HasMany(u =&gt; u.Roles)
                  .WithMany(r =&gt; r.Users)
                  .Map(c =&gt; { 
                      c.MapLeftKey("UserId");
                      c.MapRightKey("RoleId");
                      c.ToTable("UsersRoles");
                  });
  </code></pre>
  
  <p>When I am trying to add an unrelated Entity and call <code>Context.SaveChanges()</code> I receive the following error:</p>
  
  <blockquote>
    <p>Violation of PRIMARY KEY constraint 'PK_UsersRoles'. Cannot insert
    duplicate key in object 'dbo.UsersRoles'. The duplicate key value is
    (2beaf837-9034-4376-9510-b1609c54efbe,
    dcd16d00-d46e-4d48-8328-3e7b35b11ccf). The statement has been
    terminated.</p>
  </blockquote>
  
  <p>I have checked the <code>Conext.ChangeTracker.Entries()</code> for the items mentioned in the error and the Entity State is marked as Unchanged.</p>
  
  <p>The only Entity that is marked as Added is the new record I am trying to add, everything else is marked as Unchanged.</p>
  
  <p>Code for adding Entity:</p>
  
  <pre><code> RoleGroup group = Context.RoleGroups.Create();
   group.Title = roleGroupName;
   Context.Set&lt;RoleGroup&gt;().Add(group);
   Context.SaveChanges();
  </code></pre>
  
  <p>Does anyone know why this is happening?</p>