title: Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value
body: <p>ErrorMessage :</p>
  
  <blockquote>
    <p>Attaching an entity of type 'FaridCRMData.Models.Customer' failed
    because another entity of the same type already has the same primary
    key value.
    This can happen when using the <code>Attach()</code> 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>My Code:</p>
  
  <pre><code>public class FactorController : Controller
  {
      public JsonResult SaveFactor(Factor factor,int id)
      {
          if (id &gt; 0)
          {
              bool result = new FactorService.BaseService.Update(factor);
              return new JsonResult() { Data = result };
          }
  
      }
  }
  </code></pre>
  
  <p>FactorService.BaseService.cs : </p>
  
  <pre><code>public bool Update(TEntity entity)
  {
      var entry = context.Entry(entity);
      if (entry.State == EntityState.Detached || entry.State == EntityState.Modified)
      {
  
          context.Set&lt;TEntity&gt;().Attach(entity);// Error Is Here
          entry.State = EntityState.Modified;
          context.SaveChanges();
      }
      return true;
  }
  </code></pre>