Strelnikov Lev
Strelnikov Lev

Reputation: 242

Correct way to check if DocumentDB object exists

In Microsoft examples I saw two ways to check if DocumentDb object like Database, DocumentCollection, Document etc. exists :

First is by creating a query:

Database db = client.CreateDatabaseQuery().Where(x => x.Id == DatabaseId).AsEnumerable().FirstOrDefault();
if (db == null)
    {
        await client.CreateDatabaseAsync(new Database { Id = DatabaseId });
    }

The second one is by using "try catch" block:

    try
    {
       await this.client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
    }
    catch (DocumentClientException de)
    {
        if (de.StatusCode == HttpStatusCode.NotFound)
        {
           await this.client.CreateDatabaseAsync(new Database { Id = databaseName });
         }
         else
         {
             throw;
          }
    }

What is the correct way to do this procedure in terms of performance?

Upvotes: 11

Views: 6137

Answers (2)

Michal Ja
Michal Ja

Reputation: 252

I've just seen the try/catch example in one of the Microsoft provided sample project and it got me baffled, as it is plain wrong: you don't use try/catch for control flow.

Never.

This is just bad code. The new SDK provides CreateDatabaseIfNotExistsAsync which I can only hope doesn't just hide this shit. In older lib just use the query approach, unless you want to get shouted at by whoever is going to review the code.

Upvotes: 9

Aravind Krishna R.
Aravind Krishna R.

Reputation: 8003

You should use the new CreateDatabaseIfNotExistsAsync in the DocumentDB SDK instead of both these approaches, if that's what you're trying to do.

In terms of server resources (request units), a ReadDocumentAsync is slightly more lightweight than CreateDatabaseQuery, so you should use that when possible.

Upvotes: 12

Related Questions