title: 'entity of the same type already has the same primary key value' error using AutoMapper
body: <p>When I use AutoMapper, this Error occured:</p>
  
  <blockquote>
    <p>Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.</p>
  </blockquote>
  
  <p>I want to map User to UserModel when I retrive it from database. I change UserModel properties in UI and then map it again to User and Update it.
  My code is here:</p>
  
  <pre><code>public UserModel GetUserByUserId(int id)
      {
          var user = db.Users.Where(p =&gt; p.UserId == id).FirstOrDefault();
          var userModel = Mapper.Map&lt;UserModel&gt;(user);
          return userModel;
      }
  
  public void Update(UserModel userModel)
      {
          var user = Mapper.Map&lt;User&gt;(userModel);
          db.Entry(user).State = EntityState.Modified;
          db.SaveChanges();
      }
  </code></pre>
  
  <p>but if I don't Use auto mapper and write something like below code, it work correctly.</p>
  
  <pre><code>public void Update(UserModel userModel)
      {
          updatingUser.Email = userModel.Email;
          updatingUser.FirstName = userModel.FirstName;
          updatingUser.ModifiedDate = DateTime.Now;
          updatingUser.LastName = userModel.LastName;
          updatingUser.Password = userModel.Password;
          updatingUser.UserName = userModel.UserName;
  
          db.Entry(updatingUser).State = EntityState.Modified;
          db.SaveChanges();
      }
  </code></pre>
  
  <p>What should I do:</p>