title: EntityFramework fail on update entity - cannot be tracked
body: <p>I'm having this known problem with my application.
  I've tried a lot of changes with HasKey and HasAlternateKey, even HasIndex, Unique and other variations on the OnModelCreateCreating() method.
  I even re-mapped my entity but still no success!</p>
  <blockquote>
  <p>The instance of entity type 'Imoveis' cannot be tracked because
  another instance with the key value '{Cod: 91}' is already being
  tracked. When attaching existing entities, ensure that only one entity
  instance with a given key value is attached.</p>
  </blockquote>
  <p>My Update() method of my BaseRepository class:</p>
  <pre><code>    public T Update(T entity)
      {
          DbContext.Entry(entity).State = EntityState.Modified; &lt;-- Exception happens here
          DbContext.SaveChanges();
          return entity;
      }
  </code></pre>
  <p>How the Update() is called. This problem it's happening on both calls. The second try is a fail way to prevent this error:</p>
  <pre><code>public Imoveis InsertOrUpdateUniqueName(Imoveis imoveis)
  {
      try
      {
          if (imoveis.Cod &gt; 0)
              Update(imoveis);
          else
              Insert(imoveis);
          return imoveis;
      }
      catch (Exception ex)
      {
          if (imoveis.Cod &gt; 0)
          {
              if (ex is DbUpdateException)
              {
                  if ((ex.InnerException as SqlException)?.Number == 2627)
                      return UpdateImovelDuplicado(imoveis);
              }
              else if (ex is InvalidOperationException)
              {
                  var local = DbContext
                      .Set&lt;Imoveis&gt;()
                      .Local
                      .FirstOrDefault(x =&gt; x.Cod.Equals(imoveis.Cod));
                  if (local != null)
                      DbContext.Entry(local).State = EntityState.Detached;
                  return Update(imoveis);
              }
          }
  
          throw ex;
      }
  }
  </code></pre>