CreateDocumentCollectionIfNotExistsAsync does not always work

Viewed 1971

I am trying to create a collection if it does not exist.

First, I create my DocumentClient by:

public DocumentClient CreateClient(ConnectionPolicy connectionPolicy = null)
{
   return new DocumentClient(new Uri(this.AccountEndpoint), this.AccountKey, connectionPolicy);
}

Now that I have my document client (let's call it documentDbClient), I attempt to use CreateDocumentCollectionIfNotExistsAsync:

var documentDbClient = dbConnection.CreateClient();

await documentDbClient.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("mydatabase"),
            new DocumentCollection { Id = "testcollection" });

Now, I would expect this to create a collection named testcollection under my database named mydatabase. However, nothing happens. No collection is created, no exceptions are thrown.

I thought perhaps it was just slow, and so I waited 30 minutes and went back to the portal to see if my collection had been made...

It hadn't.

What is wrong?

UPDATE

Okay, so I have discovered that if I change the name of the collection that I am attempting to create, it works. I have previously created and deleted the collection many times and now it appears that Azure is failing to create it 90% of the time.

2 Answers

You should add a .Wait() to the end of database creation and then the collection creation. This will wait for both tasks to complete.

_client.CreateDatabaseIfNotExistsAsync(new Database { Id = "dbName" }).Wait();

_client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("dbName"), new DocumentCollection { Id = "collectionName" }).Wait();
Related