title: Entity Framework core - The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked
body: <p>Am currently trying out my hand in .net core and EF core.</p>
  
  <p>I have the following code to update the data</p>
  
  <pre><code>protected void Update(T entity, bool saveChanges = true)
  {
      _context.Set&lt;T&gt;().Attach(entity);
      _context.Entry(entity).State = EntityState.Modified;
      if (saveChanges) _context.SaveChanges();
  }
  </code></pre>
  
  <p>The class I am updating</p>
  
  <pre><code>public partial class Blog
  {
      public Blog()
      {
          Post = new HashSet&lt;Post&gt;();
      }
  
      public int BlogId { get; set; }
      public string Url { get; set; }
  
      public virtual ICollection&lt;Post&gt; Post { get; set; }
  }
  </code></pre>
  
  <p>When I try to update any entry the first time, it is successful. The second time I update the same entry, I get the below error:</p>
  
  <blockquote>
    <p><strong>System.InvalidOperationException:</strong> 'The instance of entity type 'Blog' 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.'</p>
  </blockquote>
  
  <p>The same occurs for each entry, successful for the first time and fails the second time.</p>
  
  <p>Additional Information:
  I get all the data using the below code:</p>
  
  <pre><code>protected IEnumerable&lt;T&gt; GetAll()
  {
      return _context.Set&lt;T&gt;().AsNoTracking().AsEnumerable();
  }
  </code></pre>
  
  <p>Display the above as a table in the view. DTO's are being used to communicate between the data and web layer.</p>
  
  <p>The context is registered in startup as below</p>
  
  <pre><code>services.AddDbContext&lt;BloggingContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  </code></pre>
  
  <p>My question is why there is an error during the second update and how to resolve it. Thanks.</p>