共用方式為


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

適用於:NoSQL

Azure Cosmos DB 中的容器會儲存項目集合。 您必須先建立容器,才能建立、查詢或管理項目。

命名容器

在 Azure Cosmos DB 中,容器類似於關聯式資料庫中的資料表。 當您建立容器時,容器名稱會成為存取容器資源和任何子資源的 URI 區段。

以下是命名容器時的一些快速規則:

  • 容器名稱不得為空白。
  • 容器名稱的長度不能超過 256 個字元。

建立之後,容器的 URI 格式如下:

https://<cosmos-account-name>.documents.azure.com/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 方法的 true 傳回型別為 ContainerResponse

下列範例顯示 Database.CreateContainerIfNotExistsAsync 方法傳回 ContainerResponse。 傳回之後,您可以剖析回應屬性,最後取得基礎 Container 物件:

// 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;

下一步

現在您已建立了容器,請使用下一個指南來建立項目。