title: Change tracking in Entity Framework Core 2.0 changed my code behavior
body: <p>That code worked fine in Entity Framework 1.0 could also be 1.1.</p>
  
  <pre><code>var pupilFound = await context.Pupils.SingleOrDefaultAsync(p =&gt; p.Id == pupil.Id);
  if (pupilFound == null)
  {
      throw new BadDataException($"{nameof(pupil.Id)} is not valid");
  }
  if (pupilFound.UserId != userId)
  {
      throw new NotAuthorizedException();
  }
  
  pupil.UserId = userId;
  context.Entry(pupil).State = EntityState.Modified;
  await contextSaveChangesAsync();
  </code></pre>
  
  <p>Now with Entity Framework Core 2.0 I got that exception with error:</p>
  
  <pre><code>Cannot be tracked because another instance of this type with the same key is already being tracked
  </code></pre>
  
  <p>A quick fix would be:</p>
  
  <pre><code>var pupilFound = await context.Pupils.AsNoTracking.SingleOrDefaultAsync(p =&gt; p.Id == pupil.Id);
  </code></pre>
  
  <p>That way the tracking is disabled, but that defeats the purpose of the AsNoTracking method regarding the <strong>official recommendation</strong>:</p>
  
  <p><a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.changetracking.changetracker.querytrackingbehavior?view=efcore-2.0" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.changetracking.changetracker.querytrackingbehavior?view=efcore-2.0</a></p>
  
  <pre><code>Disabling change tracking is useful for read-only scenarios because it avoids
          //     the overhead of setting up change tracking for each entity instance. You should
          //     not disable change tracking if you want to manipulate entity instances and persist
          //     those changes to the database using Microsoft.EntityFrameworkCore.DbContext.SaveChanges
  </code></pre>
  
  <p>How else would update the pupil with all its properties coming from the client?</p>