共用方式為


使用 .NET 在 Azure Cosmos DB 中為 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 方法的真實回傳類型為 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;

後續步驟

現在你已經建立了容器,請使用下一個指南來製作物品。