title: The instance of entity type 'TestType' cannot be tracked because another instance of this type with the same key is already being tracked
body: <p>I am getting the below exception when I try to do:</p>
  
  <pre><code>    context.Entry(testType).State = EntityState.Modified;
  
  
  System.InvalidOperationException: The instance of entity type 'TestType' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
     at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges)
     at Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry.set_State(EntityState value)
  </code></pre>
  
  <p>I do not see any code where another TestType instance with a same key is already tracked!</p>
  
  <p>The testtypes from the database are loaded via <code>.AsNoTracking();</code></p>
  
  <p>So where in this code are instances of TestType with the same key where I do an RemoveRange/AddRange operation on? That would mean that my TestTypeComparer is broken?</p>
  
  <p>What I try to do here is to let the user <strong>batch save changed/add/deleted entities in one go:</strong></p>
  
  <pre><code> public async Task&lt;IEnumerable&lt;TestType&gt;&gt; SaveTestTypesAsync(List&lt;TestType&gt; testTypes, int schoolyearId, int schoolclassId, int subjectId)
          {
              var testTypesFromDatabase = await context.TestTypes
                                            .Include(t =&gt; t.Subject)
                                            .Include(s =&gt; s.Schoolclass)
                                            .Where(p =&gt;
                                            p.Schoolclass.Id == schoolclassId &amp;&amp;
                                            p.Subject.Id == subjectId)
                                            .AsNoTracking()
                                            .ToListAsync();
  
              var schoolclass = new Schoolclass { Id = schoolclassId };
              var subject = new Subject { Id = subjectId };
              var schoolyear = new Schoolyear { Id = schoolyearId };
              foreach (var testType in testTypes)
              {
                  testType.Schoolclass = schoolclass;
                  testType.Subject = subject;
                  testType.Schoolyear = schoolyear;
              }
  
              var testTypesToRemove = testTypesFromDatabase.Except(testTypes, new TestTypeComparer()).ToList();
              context.TestTypes.RemoveRange(testTypesToRemove);
  
              var testTypesToAdd = testTypes.Where(t =&gt; t.Id == 0).ToList();  // 
              context.TestTypes.AddRange(testTypesToAdd);
  
              var modifiedTestTypesToUpdate = testTypes.Except(testTypesToAdd.Concat(testTypesToRemove).ToList(), new TestTypeComparer()).ToList();
              foreach (var testType in modifiedTestTypesToUpdate)
              {
                  context.Entry(testType).State = EntityState.Modified;
              }
  
              context.Attach(schoolclass);      
              context.Attach(subject);
              context.Attach(schoolyear);
  
              await context.SaveChangesAsync();
  
              return await this.GetTestTypesConfigurationAsync(schoolclassId, subjectId);
          }
  
  
  public class TestTypeComparer : IEqualityComparer&lt;TestType&gt;
  {
      public bool Equals(TestType x, TestType y)
      {
          return x.Id == y.Id;
      }
  
      public int GetHashCode(TestType obj)
      {
          return obj.Id.GetHashCode();
      }
  }
  
  public class TestType
      {
          public TestType()
          {
              Tests = new HashSet&lt;Test&gt;();
          }
  
          public int Id { get; set; }
          public string Name { get; set; }
          public int Weight { get; set; }
          public ISet&lt;Test&gt; Tests { get; set; }
          public Schoolyear Schoolyear { get; set; }  
          public Schoolclass Schoolclass { get; set; }
          public int SchoolclassId { get; set; }
          public Subject Subject { get; set; }
          public int SubjectId { get; set; }
          public int SchoolyearId { get; set; }
      }
  </code></pre>
  
  <p><em>Anyone can help me please I can`t spot the double tracked entity with same key.</em></p>
  
  <p><em>I just assume the problem has something to do how I determine the Added/Modified/Deleted entities.</em></p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I have now logged all the tracker changes just before I set the State.Modified for all TestTypesToUpdate:</p>
  
  <pre><code>State: Deleted | Type: TestType | Id-Value: 12
  State: Unchanged | Type: Schoolclass | Id-Value: 1
  State: Unchanged | Type: TestType | Id-Value: 8
  State: Unchanged | Type: Subject | Id-Value: 1
  State: Deleted | Type: TestType | Id-Value: 13
  State: Added | Type: TestType | Id-Value: -2147482647
  State: Detached | Type: Schoolclass | Id-Value: 1
  State: Added | Type: Schoolyear | Id-Value: 1
  State: Detached | Type: Subject | Id-Value: 1
  State: Added | Type: TestType | Id-Value: -2147482646
  </code></pre>
  
  <p>It seems yeah ... some entities are already tracked. Seems I have to invest some more if/else with the change tracker and then decide what to do.</p>
  
  <p>But I can not believe that I am the first doing something like that, havent found anything on google.</p>