共用方式為


使用 Azure DocumentDB 建立 .NET 主控台應用程式

本指南示範如何建立一個 .NET 主控台應用程式,以連接 Azure DocumentDB 叢集。 您已設定開發環境、使用 Azure.Identity 適用於 .NET 的 Azure SDK 連結庫進行驗證,並與資料庫互動以建立、查詢和更新檔。

先決條件

  • Azure 訂用帳戶

    • 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
  • 一個現有的 Azure DocumentDB 叢集

  • 為叢集設定 Microsoft Entra 驗證,且您的身分識別已獲授與 root 角色。

  • 最新版的 .NET

擷取 Microsoft Entra 租用戶中繼資料

若要在 TokenCredential 中使用 Azure.Identity 類別來擷取存取令牌,您需要 Microsoft Entra 租使用者的唯一標識符。 在此必要步驟中,使用 Azure CLI 來擷取和記錄 tenantId 值。

  1. 使用 az account show取得目前登入 Azure 訂用帳戶的詳細數據。

    az account show
    
  2. 命令會輸出包含各種欄位的 JSON 回應。

    {
      "environmentName": "AzureCloud",
      "homeTenantId": "eeeeffff-4444-aaaa-5555-bbbb6666cccc",
      "id": "dddd3d3d-ee4e-ff5f-aa6a-bbbbbb7b7b7b",
      "isDefault": true,
      "managedByTenants": [],
      "name": "example-azure-subscription",
      "state": "Enabled",
      "tenantId": "eeeeffff-4444-aaaa-5555-bbbb6666cccc",
      "user": {
        "cloudShellID": true,
        "name": "kai@adventure-works.com",
        "type": "user"
      }
    }
    
  3. 記錄 屬性的值 tenantId 。 此屬性是您Microsoft Entra 租使用者的唯一標識碼,有時稱為 租用戶標識符。 您可以在後續區段內的步驟中使用此值。

設定主控台應用程式

接下來,建立新的主控台應用程式專案,並匯入必要的函式庫來驗證您的叢集。

  1. 在空的目錄中,建立新的 .NET 控制台應用程式。

    dotnet new console
    
  2. 從 NuGet 匯入 Azure.Identity 套件。

    dotnet add package Azure.Identity
    
  3. 接下來,匯入 MongoDB.Driver 套件。

    dotnet add package MongoDB.Driver
    
  4. 建置 .NET 專案

    dotnet build
    

連接至叢集

現在,使用 Azure.Identity 庫取得 TokenCredential,以用來連線到您的叢集。 官方 MongoDB 驅動程式有一個特殊的介面,必須實作才能從 Microsoft Entra 取得令牌,以在連線到叢集時使用。

  1. Program.cs 檔案中,使用這些 Azure.IdentityMongoDB.Driver 命名空間的區塊新增。

    using Azure.Identity;
    using MongoDB.Driver;
    
  2. 在個別的檔案中建立新類別,以實作 MongoDB.Driver.Authentication.Oidc.IOidcCallback 介面的所有必要成員。

    using Azure.Core;
    using MongoDB.Driver.Authentication.Oidc;
    
    internal sealed class AzureIdentityTokenHandler(
        TokenCredential credential,
        string tenantId
    ) : IOidcCallback
    {
        private readonly string[] scopes = ["https://ossrdbms-aad.database.windows.net/.default"];
    
        public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken)
        {
            AccessToken token = credential.GetToken(
                new TokenRequestContext(scopes, tenantId: tenantId),
                cancellationToken
            );
    
            return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
        }
    
        public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken)
        {
            AccessToken token = await credential.GetTokenAsync(
                new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId),
                cancellationToken
            );
    
            return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
        }
    }
    

    小提示

    為了說明目的,這個類別的名稱為 AzureIdentityTokenHandler。 您可以將這個類別命名為您想要的任何名稱。 本指南的其餘部分假設類別名為 AzureIdentityTokenHandler

  3. 返回 Program.cs 檔案的編輯器。

  4. 使用您現有叢集的名稱建立字串變數。 然後,使用該變數,利用 MongoUrl.Create 來建立一個新的執行個體類型 MongoUrl

    string clusterName = "<azure-documentdb-cluster-name>";
    
    MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");
    
  5. 請使用前述步驟中建立的MongoSettings設定以及 Azure DocumentDB 的標準最佳實例設定來配置一個新MongoUrl實例。

    MongoClientSettings settings = MongoClientSettings.FromUrl(url);
    
    settings.UseTls = true;
    settings.RetryWrites = false;
    settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2);
    
  6. 建立類型 DefaultAzureCredential的新認證。

    DefaultAzureCredential credential = new();
    

    小提示

    您可以在這裡使用任何類型的 TokenCredential 認證。 DefaultAzureCredential 是早期開發案例中最無摩擦的選項。

  7. 為您實作 IOidcCallback 的類別建立新的執行個體,並使用您稍早在本指南中記錄的租用戶 ID 進行設定。

    string tenantId = "<microsoft-entra-tenant-id>";
    
    AzureIdentityTokenHandler tokenHandler = new(credential, tenantId);
    
  8. 使用 MongoCredential.CreateOidcCredential 並傳入您的自訂處理常式回撥實作,為您的設定設定認證。

    settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler);
    
  9. 將設定凍結,然後創建MongoClient的新實例。

    settings.Freeze();
    
    MongoClient client = new(settings);
    
    Console.WriteLine("Client created");
    

執行一般作業

最後,使用官方程式庫處理資料庫、集合和文件的常見工作。 在這裡,您可以使用與 MongoDB 或 DocumentDB 互動的相同類別和方法來管理您的集合和專案。

  1. 藉由在獨立的檔案中建立自訂的紀錄類型來代表您的文件。

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

    小提示

    為了說明目的,此結構的名稱為 Product。 本指南的其餘部分假設您已定義此結構。

  2. 返回 Program.cs 檔案。

  3. 使用 MongoClient.GetDatabase 取得資料庫指標。

    string databaseName = "<database-name>";
    
    IMongoDatabase database = client.GetDatabase(databaseName);
    
    Console.WriteLine("Database pointer created"); 
    
  4. 然後,使用資料庫指標,以使用 IMongoDatabase.GetCollection<> 取得集合的指標。

    string collectionName = "<collection-name>";
    
    IMongoCollection<Product> collection = database.GetCollection<Product>(collectionName);
    
    Console.WriteLine("Collection pointer created"); 
    
  5. 使用 IMongoCollection<>.ReplaceOneAsync 方法建立及 upsert 兩份文件。

    Product classicSurfboard = new(
        id: "bbbbbbbb-1111-2222-3333-cccccccccccc",
        category: "gear-surf-surfboards",
        name: "Kiama Classic Surfboard",
        quantity: 25,
        price: 790.00m,
        clearance: false
    );
    
    Product paddleKayak = new(
        id: "cccccccc-2222-3333-4444-dddddddddddd",
        category: "gear-paddle-kayaks",
        name: "Lastovichka Paddle Kayak",
        quantity: 10,
        price: 599.99m,
        clearance: true
    );
    
    await collection.ReplaceOneAsync<Product>(
        doc => doc.id == classicSurfboard.id,
        classicSurfboard,
        new ReplaceOptions { IsUpsert = true }
    );
    
    Console.WriteLine($"Upserted document:\t{classicSurfboard.id}");
    
    await collection.ReplaceOneAsync<Product>(
        doc => doc.id == paddleKayak.id,
        paddleKayak,
        new ReplaceOptions { IsUpsert = true }
    );
    
    Console.WriteLine($"Upserted document:\t{paddleKayak.id}");
    
  6. 使用 IMongoCollection<>.FindIFindFluent<,>.SingleAsync從集合讀取單一檔。 使用篩選來指定您想要尋找的特定檔。

    Product document = await collection.Find(
        doc => doc.id == "cccccccc-2222-3333-4444-dddddddddddd"
    ).SingleAsync();
    
    Console.WriteLine($"Found document:\t{document.name}");
    
  7. 使用相同 Find 方法查詢符合篩選條件的所有檔。 使用篩選來定義特定屬性 (例如category) 和特定值 (例如 )。gear-surf-surfboards 使用 IFindFluent<,>.ToListAsync列舉結果。

    List<Product> documents = await collection.Find(
        doc => doc.category == "gear-surf-surfboards"
    ).ToListAsync();
    
    foreach (Product doc in documents)
    {
        Console.WriteLine($"Queried document:\t{doc}");
    }
    
  8. 使用 IMongoCollection<>.DeleteOneAsync 和 篩選,從集合中刪除特定檔。

    await collection.DeleteOneAsync(
        doc => doc.id == "bbbbbbbb-1111-2222-3333-cccccccccccc"
    );
    
    Console.WriteLine($"Deleted document");
    
  9. 將所有 程式代碼檔案儲存在專案中。

  10. 使用 dotnet run 執行專案

    dotnet run
    
  11. 觀察執行中應用程式的輸出。

    Client created
    Database pointer created
    Collection pointer created
    Upserted document:      bbbbbbbb-1111-2222-3333-cccccccccccc
    Upserted document:      cccccccc-2222-3333-4444-dddddddddddd
    Found document: Lastovichka Paddle Kayak
    Queried document:       Product { id = bbbbbbbb-1111-2222-3333-cccccccccccc, category = gear-surf-surfboards, name = Kiama Classic Surfboard, quantity = 25, price = 790.00, clearance = False }
    Deleted document