title: Entity Framework - An item with the same key has already been added. - Error when trying to define foreign key relationship
body: <p>I have an entity with a foreign key relationship to an asp.net membership provider users table.</p>
  
  <p>This portion of the model looks like this:</p>
  
  <p><img src="https://i.stack.imgur.com/sQFsL.png" alt="alt text"></p>
  
  <p>I can't seem to assign the foreign key relationship when inserting the Users table record, the record containing the foreign key to the <code>aspnet_Users</code> table. I keep getting the error: </p>
  
  <blockquote>
    <p>An item with the same key has already
    been added.</p>
  </blockquote>
  
  <p>The code I'm using looks like:</p>
  
  <pre><code>UserAdmin userToAdd = new UserAdmin();
  ...
  userToAdd.aspnet_Users = membershipUser;
  //line above OR line below
  userToAdd.aspnet_UsersReference.EntityKey = new System.Data.EntityKey("ProjectEntities.aspnet_Users", "UserId", membershipUser.UserId);
  
  db.AddToUsers(userToAdd);
  db.SaveChanges();
  </code></pre>
  
  <p>Is the issue that I'm asking the EF to add a new <code>aspnet_Users</code> table record (the record for the associated primary key table) when that record is already there?</p>
  
  <p>How would I assign a foreign key value to an entity where the primary key record already exists?</p>
  
  <p>Updated test code block:</p>
  
  <pre><code>MembershipUser membershipUser = Membership.CreateUser("blah@blah.com", "pass", "blah@blah.com");
  
  Entities db = new Entities();
  UserAdmin newUser = new UserAdmin();
  newUser.Name = "blah";
  newUser.DateAdded = DateTime.Now;
  
  Guid key = new Guid(membershipUser.ProviderUserKey.ToString());
  aspnet_Users membershipUserRecord = db.aspnet_Users.Where(u =&gt; u.UserId == key).FirstOrDefault();
  newUser.aspnet_Users = membershipUserRecord;
  //newUser.aspnet_UsersReference.EntityKey = new System.Data.EntityKey("Entities.aspnet_Users", "UserId", membershipUserRecord.UserId);
  db.ObjectStateManager.ChangeObjectState(membershipUserRecord, EntityState.Unchanged);
  
  db.AddToUsers(newUser);
  db.SaveChanges();
  </code></pre>
  
  <p>This code generates the error:</p>
  
  <blockquote>
    <p>An item with the same key has already been added.</p>
  </blockquote>