title: Entity Framework Updating with Stub causes Primary Key Violation
body: <p>I have the following common tables with the relationships setup in a many to many fashion in my entity model:</p>
  
  <pre><code>Users - UserCodePK, UserName
  UserGroups - UserCodeFK,GroupCodeFK
  Groups - GroupCodePK,GroupDescription
  </code></pre>
  
  <p>My Code when trying to add a user:</p>
  
  <pre><code>public static string CreateUser(User user)
  {
      using (var dbContext = new DCSEntities())
      {
          User u = new User
                  {
                      UserCodePK = "NewUser",
                      txtUserName = "New User Name
                  };
  
          u.Groups.Add(new UserGroup {GroupCode = "ADMIN"});
          u.Groups.Add(new UserGroup {GroupCode = "SUPER"});
          dbContext.Users.AddObject(user);
          dbContext.SaveChanges();
          }
  }   
  </code></pre>
  
  <p>The error that I'm getting is :</p>
  
  <pre><code>"Violation of PRIMARY KEY constraint 'PK_Groups'. Cannot insert duplicate key in object 'dbo.Groups'. The duplicate key value is (ADMIN)"
  </code></pre>
  
  <p>Basically saying that I'm trying to add the group "ADMIN", which already exists in that table. I thought that by using the stub as above, that I won't need to go the database to fetch the "ADMIN" group and add it to the User object.
  Any advice on how to get rid of the error?</p>
  
  <p><strong>EDIT:</strong> My Completed Code Based on the Suggestions Below(I hope this is in the right place?)</p>
  
  <p>UI Method</p>
  
  <pre><code>protected void CreateUser()
  {
      User user = new User();
      user.UserCodePK = txtUserCode.Text;
      user.UserName = txtUserName.Text;                
      List&lt;UserGroup&gt; userGroups = new List&lt;UserGroup&gt;();
      for (int i = 0; i &lt; chkListGroups.Items.Count; i++)
      {
          if (chkListGroups.Items[i].Selected == true)
          {
              userGroups.Add(new UserGroup { GroupCodePK = chkListGroups.Items[i].Value });
          }
      }
  
      string userCode = BLL.UserFunctions.CreateUser(user, userGroups);
  }
  </code></pre>
  
  <p>BLL Method</p>
  
  <pre><code>public static string CreateUser(User user, List&lt;UserGroup&gt; userGroups)
  {
      return UserDAL.CreateUser(user,userGroups);
  }
  </code></pre>
  
  <p>DAL Method</p>
  
  <pre><code>public static string CreateUser(User user,List&lt;UserGroup&gt; userGroups)
  {
      using (var dbContext = new DCSEntities())
      {
          foreach (UserGroup g in userGroups)
          {
              var ug = new UserGroup { GroupCode = g.GroupCode };
              dbContext.UserGroups.Attach(ug);
              user.UserGroups.Add(ug);
          }
          dbContext.Users.AddObject(user);
          dbContext.SaveChanges();
          return user.UserCode;
      }
  }
  </code></pre>