检查DocumentDB对象是否存在的正确方法 [英] Correct way to check if DocumentDB object exists

查看:78
本文介绍了检查DocumentDB对象是否存在的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Microsoft示例中,我看到了两种方法来检查是否存在DocumentDb对象,例如Database,DocumentCollection,Document等:

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

首先是通过创建查询:

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

第二个是通过使用"try catch"块:

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?

推荐答案

如果您要这样做,则应该在DocumentDB SDK中使用新的CreateDatabaseIfNotExistsAsync而不是这两种方法.

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

就服务器资源(请求单位)而言,ReadDocumentAsyncCreateDatabaseQuery稍微轻巧一些,因此应尽可能使用它.

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

这篇关于检查DocumentDB对象是否存在的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆