title: EF Core - Insert then update an entry
body: <p>In a WebApi method I need, if an element not exist, insert it and after a few operations update it.</p>
  
  <p>The code is the following:</p>
  
  <pre><code>Entry existingEntry = await _repo.GetEntryByIdAsync(id);
  
  existingEntry = await _repo.AddNewEntryAsync(existingAccred);
  
  // Some code...
  
  // Update
  existingAccred.IdField = myField;
  await _repo.UpdateEntryAsync(existingEntry);
  </code></pre>
  
  <p>The repo is the following:</p>
  
  <pre><code>    public async Task&lt;Entry&gt; GetEntryByIdAsync(int myId)
      {
          var result = from entry in _ctx.Set&lt;DALENTRY&gt;()
              where entry.ID == myId
              select new Entry
              {
                  ID = entry.IdEntry,
              };
  
          return await result.AsNoTracking().FirstOrDefaultAsync();
      }
  
      public async Task&lt;Entry&gt; AddNewEntryAsync(Entry newEntry)
      {
          DALENTRY entry = new DALENTRY()
          {
              GUID = newEntry.GUID,
          };
  
          _ctx.Add(entry);
          await _ctx.SaveChangesAsync();
  
          newEntry.IdEntry = entry.ID;
  
          return newEntry;
      }
  
      public async Task&lt;Entry&gt; UpdateEntryAsync(Entry updateEntry)
      {
          DALENTRY entry = new DALENTRY()
          {
              ID = updateEntry.IdEntry,
              FIELD= updateEntry.IdField,
          };
  
          _ctx.Update(entry);
          await _ctx.SaveChangesAsync();
  
          return updateEntry;
      }
  </code></pre>
  
  <p>But when I perform the update I'm getting is the following error:</p>
  
  <blockquote>
    <p>An unhandled exception occurred while processing the request.</p>
    
    <p>InvalidOperationException: The instance of entity type 'DALENTRY' 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
    'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the
    conflicting key values.
    Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.Add(TKey
    key, InternalEntityEntry entry)</p>
  </blockquote>
  
  <p>The repo is registered as Transient like:</p>
  
  <pre><code>services.AddTransient&lt;EntryRepository&gt;();
  </code></pre>
  
  <p>I tried using Detach after the insert, but using it the update is clearing all the non updated fields. I can't remember what is causing this issue.</p>