title: EF Core 'another instance is already being tracked'
body: <p>I have a problem updating an entity in .Net Core 2.2.0 using EF Core 2.2.3. </p>
  
  <blockquote>
    <p>An error occurred while saving changes. Error details:
    The instance of entity type 'Asset' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using </p>
  </blockquote>
  
  <p>This is how the DB Context is registered:</p>
  
  <p>services.AddDbContext(options =></p>
  
  <pre><code>options.UseSqlServer(Configuration.GetConnectionString("DbConnection")), ServiceLifetime.Scoped);
  </code></pre>
  
  <p><em>The <code>Scoped</code> lifetime is set by default but I wrote it to be more easy to understand.</em></p>
  
  <p>The <code>Anomaly</code> object is got like this:</p>
  
  <pre><code>public IQueryable&lt;Anomaly&gt; GetAll()
      {return _context.Anomalies.Include(a =&gt; a.Asset).Include(a =&gt; a.Level)
  }
  
  public async Task&lt;Anomaly&gt; GetAnomaly(int anomalyId, User user)
  {
      var anomaly = await GetAll()
          .FirstOrDefaultAsync(a =&gt; a.Id == anomalyId);
  
      return anomaly;
  }
  </code></pre>
  
  <p>And the <code>Update()</code> method looks like this:</p>
  
  <pre><code>using (var transaction = _context.Database.BeginTransaction())
  {
      try
      {
          _context.Anomalies.Update(anomaly);
          _context.SaveChanges();
  
          transaction.Commit();
      }
      catch (Exception ex)
      {
          transaction.Rollback();
          throw;
      }
  }
  </code></pre>
  
  <p><em>It contains some checks before this transaction, but none relevant enough in this context.</em></p>
  
  <p>This is where I get the error with <em>instance already being tracked</em>. I can't understand how this happens .. If the context is <code>Scoped</code>, then </p>
  
  <blockquote>
    <p>... "a new instance of the service will be created for each scope", in this case, for each request</p>
  </blockquote>
  
  <p>If my context on the PUT request is different from the context of the GET request, how is the entity already being tracked? How does this work at the most basic levels?</p>
  
  <p>The only way to make it work is to set the state for all entries from the <code>ChangeTracker</code> to <code>EntityState.Detached</code>. Then it works.. but it makes no sense, at least to my current knowledge..</p>
  
  <p>I found <a href="https://stackoverflow.com/questions/42607030/ef-the-instance-of-entity-type-x-cannot-be-tracked-because-another-instance-of">this question</a> but with no valid answer, only with workarounds and assumptions about how EF does the tracking.</p>
  
  <hr>
  
  <blockquote>
    <p><strong>UPDATE</strong>
    Here is a link to bitbucket with a sample recreating this problem: <a href="https://bitbucket.org/marian_simonca/ef-core-update/src/master/" rel="noreferrer">EF Core Update Sample</a></p>
  </blockquote>
  
  <p>I serialized the objects retrieved from the context.</p>
  
  <p>With Tracking on the LEFT &lt;====> With NO tracking on the RIGHT
  <a href="https://i.stack.imgur.com/9N9vK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9N9vK.png" alt="With Tracking on the LEFT &lt;====&gt; With NO tracking on the RIGHT"></a></p>