使用 .NET 在 Azure Cosmos DB for NoSQL 中创建容器

Azure Cosmos DB 中的容器存储项集。 必须先创建容器,然后才能创建、查询或管理项。

为容器命名

在 Azure Cosmos DB 中,容器类似于关系数据库中的表。 创建容器时,容器名称将形成用于访问容器资源和任何子项的 URI 段。

下面是命名容器时的一些快速规则:

  • 容器名称不得为空。
  • 容器名称不能超过 256 个字符。

创建后,容器的 URI 采用以下格式:

https://<cosmos-account-name>.documents.azure.cn/dbs/<database-name>/colls/<container-name>

小窍门

有关容器名称限制的详细信息,请参阅 服务配额和限制

创建容器

若要创建容器,请调用以下方法之一:

异步创建容器

以下示例异步创建容器:

// New instance of Container class referencing the server-side container
Container container1 = await database.CreateContainerAsync(
    id: "products-1",
    partitionKeyPath: "/category",
    throughput: 400
);

如果已存在同名的数据库,该方法 Database.CreateContainerAsync 将引发异常。

如果容器尚不存在,则异步创建容器

以下示例仅在帐户中尚不存在容器时才异步创建容器:

// New instance of Container class referencing the server-side container
Container container2 = await database.CreateContainerIfNotExistsAsync(
    id: "products-2",
    partitionKeyPath: "/category",
    throughput: 400
);

Database.CreateContainerIfNotExistsAsync仅当新容器尚不存在时,该方法才会创建一个新容器。 如果多次运行同一代码,则此方法对于避免错误非常有用。

分析响应

到目前为止,所有示例中,异步请求的响应被立即强制转换为 Container 类型。 你可能想要分析有关响应的元数据,包括标头和 HTTP 状态代码。 Database.CreateContainerAsyncDatabase.CreateContainerIfNotExistsAsync 方法的真正返回类型为 ContainerResponse

以下示例演示 Database.CreateContainerIfNotExistsAsync 方法返回 ContainerResponse。 返回后,可以分析响应属性,然后最终获取基础 容器 对象:

// New instance of Container class referencing the server-side container
ContainerResponse response = await database.CreateContainerIfNotExistsAsync(
    id: "products-3",
    partitionKeyPath: "/category",
    throughput: 400
);
// Parse additional response properties
Container container3 = response.Container;

后续步骤

现在您已经创建了一个容器,请使用下一个指南来创建元素。