共用方式為


快速入門:搭配適用於 .NET 的 Azure SDK 使用適用於 NoSQL 的 Azure Cosmos DB

在本快速入門中,您會使用適用於 .NET 的 Azure SDK 來部署適用於 NoSQL 的基本 Azure Cosmos DB 應用程式。 適用於 NoSQL 的 Azure Cosmos DB 是無架構資料存放區,可讓應用程式將非結構化數據儲存在雲端中。 使用適用於 .NET 的 Azure SDK 查詢容器中的數據,並在個別專案上執行一般作業。

API 參考文件 | 程式庫原始程式碼 | 套件 (NuGet) | Azure Developer CLI

必要條件

  • Azure Developer CLI
  • Docker 桌面
  • .NET 9.0

如果您沒有 Azure 帳戶,請在您開始之前先建立 免費帳戶

初始化專案

使用 Azure 開發人員 CLI (azd) 建立適用於 NoSQL 的 Azure Cosmos DB 帳戶,並部署容器化範例應用程式。 應用程式範例使用用戶端程式庫管理、建立、讀取和查詢樣本資料。

  1. 在空的目錄中開啟終端機。

  2. 如果您尚未通過驗證,請使用 azd auth login向 Azure 開發人員 CLI 進行驗證。 依照工具指定的步驟,使用您慣用的 Azure 認證向 CLI 進行驗證。

    azd auth login
    
  3. 使用 azd init 來初始化專案。

    azd init --template cosmos-db-nosql-dotnet-quickstart
    
  4. 在初始化期間,請設定唯一的環境名稱。

  5. 使用 azd up 部署 Azure Cosmos DB 帳戶。 Bicep 範本也會部署範例 Web 應用程式。

    azd up
    
  6. 在布建程式期間,選取您的訂用帳戶、所需的位置和目標資源群組。 等候佈建程序完成。 此流程「大約需要五分鐘」的時間。

  7. Azure 資源佈建完成後,輸出將包含正在執行的 Web 應用程式的 URL。

    Deploying services (azd deploy)
    
      (✓) Done: Deploying service web
    - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
    
    SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
    
  8. 請使用主控台中的 URL,以在瀏覽器中導覽至您的 Web 應用程式。 觀察執行中應用程式的輸出。

螢幕擷取畫面,其中顯示執行中的 Web 應用程式。

安裝用戶端程式庫

用戶端程式庫可透過 NuGet 以 Microsoft.Azure.Cosmos 套件形式提供。

  1. 開啟終端機,然後導覽至 /src/web 資料夾。

    cd ./src/web
    
  2. 如果尚未安裝,則請使用 Microsoft.Azure.Cosmos 來安裝 dotnet add package 套件。

    dotnet add package Microsoft.Azure.Cosmos --version 3.*
    
  3. 也請安裝 Azure.Identity 套件 (如果尚未安裝)。

    dotnet add package Azure.Identity --version 1.12.*
    
  4. 開啟並檢閱 src/web/Cosmos.Samples.NoSQL.Quickstart.Web.csproj 檔案,以驗證 Microsoft.Azure.CosmosAzure.Identity 項目都存在。

匯入程式庫

Azure.IdentityMicrosoft.Azure.Cosmos 命名空間匯入您的應用程式程式代碼。

using Azure.Identity;

using Microsoft.Azure.Cosmos;

物件模型

名稱 描述
CosmosClient 此類別是主要用戶端類別,並且用來管理全帳戶中繼資料或資料庫。
Database 此類別代表帳戶內的資料庫。
Container 此類別主要用來對容器或容器內所儲存的項目執行讀取、更新和刪除作業。
PartitionKey 此類別代表邏輯分區鍵。 許多常見的作業和查詢都需要此類別。

程式碼範例

範本中的程式碼範例使用 cosmicworks 資料庫和 products 容器。 products 容器包含每個產品的名稱、類別、數量、唯一識別碼和銷售旗標這類詳細資料。 容器使用 /category 屬性作為邏輯分割區索引鍵。

驗證用戶端

此範例會建立 CosmosClient 類別的新執行個體,並使用 DefaultAzureCredential 執行個體來進行驗證。

DefaultAzureCredential credential = new();

CosmosClient client = new(
    accountEndpoint: "<azure-cosmos-db-nosql-account-endpoint>",
    tokenCredential: new DefaultAzureCredential()
);

取得資料庫

使用 client.GetDatabase 來擷取名為 cosmicworks 的現有資料庫。

Database database = client.GetDatabase("cosmicworks");

找一個容器

使用 products 來擷取現有 database.GetContainer 容器。

Container container = database.GetContainer("products");

建立項目

建置 C# 記錄類型,而此類型具有所有您想要序列化成 JSON 的成員。 在此範例中,此類型具有唯一識別碼,以及類別、名稱、數量、價格和銷售的欄位。

public record Product(
    string id,
    string category,
    string name,
    int quantity,
    decimal price,
    bool clearance
);

使用 container.UpsertItem,以在容器中建立項目。 此方法會有效地「更新插入」資料,如果該資料已存在,則會取代原資料。

Product item = new(
    id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
    category: "gear-surf-surfboards",
    name: "Yamba Surfboard",
    quantity: 12,
    price: 850.00m,
    clearance: false
);

ItemResponse<Product> response = await container.UpsertItemAsync<Product>(
    item: item,
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

讀取項目

使用唯一識別碼 (id) 和分割區索引鍵欄位,來執行點讀取作業。 使用 container.ReadItem 有效率地擷取特定項目。

ItemResponse<Product> response = await container.ReadItemAsync<Product>(
    id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

查詢項目

使用 container.GetItemQueryIterator,以對容器中的多個項目執行查詢。 使用此參數化查詢,來尋找所指定類別內的所有項目:

SELECT * FROM products p WHERE p.category = @category
string query = "SELECT * FROM products p WHERE p.category = @category"

var query = new QueryDefinition(query)
  .WithParameter("@category", "gear-surf-surfboards");

using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
    queryDefinition: query
);

使用 feed.ReadNextAsync 以重複查看結果的每個頁面,以剖析已分頁的查詢結果。 使用 feed.HasMoreResults 來判斷每個迴圈開頭是否留下任何結果。

List<Product> items = new();
while (feed.HasMoreResults)
{
    FeedResponse<Product> response = await feed.ReadNextAsync();
    foreach (Product item in response)
    {
        items.Add(item);
    }
}

探索您的資料

使用適用於 Azure Cosmos DB 的 Visual Studio Code 擴充功能來探索您的 NoSQL 數據。 您可以執行核心資料庫作業,包括但不限於:

  • 使用剪貼簿或查詢編輯器執行查詢
  • 修改、更新、建立和刪除項目
  • 從其他來源匯入大量數據
  • 管理資料庫和容器

如需詳細資訊,請參閱 如何使用 Visual Studio Code 擴充功能來探索適用於 NoSQL 數據的 Azure Cosmos DB。

清除資源

當您不再需要範例應用程式或資源時,請移除對應的部署和所有資源。

azd down