title: Entity with id already exists and does not exist simultaneously in CosmosDB
body: <p>I'm banging my head against the wall on this one.</p>
  <p>I've got a function that is basically an Upsert called <code>TryCreateOrUpdate</code>. I do realize that an upsert function now exists, but this is some older code. Here's the function:</p>
  <pre class="lang-cs prettyprint-override"><code>public static async Task&lt;string&gt; TryCreateOrUpdate&lt;T&gt;(T data) where T : ViewModelBase
  {
      var options = string.IsNullOrWhiteSpace(data.PartitionKey) ? null : new RequestOptions { PartitionKey = new PartitionKey(data.PartitionKey) };
      try
      {
          var response = await Client.CreateDocumentAsync(Collection.SelfLink, data, options, true);
      }
      catch (DocumentClientException dce)
      {
          switch (dce.StatusCode.Value)
          {
              ...
              case HttpStatusCode.Conflict:
                  try
                  {
                      var link = UriFactory.CreateDocumentUri(_databaseId, _collectionId, data.Id);
                      await Client.ReplaceDocumentAsync(link, item, options);
                  }
                  catch (Exception e)
                  {
                      return $&quot;There was an error updating the document.&quot;;
                  }
                  break;
              default:
                  ...
          }
      }
      catch (Exception e)
      {
          return &quot;There was an unknown error creating the document.&quot;;
      }
      return &quot;OK&quot;;
  }
  </code></pre>
  
  <p>I'm trying to insert a document with an id that is 6 digits as a string.</p>
  <p>I checked my Cosmos DB and I can confirm that there is no document in the database with the id which I am trying to upsert. So it should result in a create.</p>
  <p>The line that creates the document throws a <code>DocumentClientException</code>:</p>
  <blockquote>
  <p>Entity with the specified id already exists in the system.</p>
  </blockquote>
  <p>However, the replace line of code throws this exception:</p>
  <blockquote>
  <p>Entity with the specified id does not exist in the system.</p>
  </blockquote>
  <p>Um, what? Does it exist or not?!</p>
  <p>As I said, I check before I run this and the document doesn't exist.</p>
  <p>I even tried changing all this code to use the newer <code>UpsertDocumentAsync</code> and I still get the error</p>
  <blockquote>
  <p>Entity with id already exists in the system</p>
  </blockquote>
  <p>even though, as I've said, the document DOES NOT EXIST.</p>