快速入門:建置 .NET 主控台應用程式來管理 Azure Cosmos DB SQL API 資源Quickstart: Build a .NET console app to manage Azure Cosmos DB SQL API resources

適用於: SQL API

開始使用適用於 .NET 的 Azure Cosmos DB SQL API 用戶端程式庫。Get started with the Azure Cosmos DB SQL API client library for .NET. 請依照此文件中的步驟安裝 .NET 套件、建置應用程式,並針對 Azure Cosmos DB 中儲存的資料嘗試使用基本 CRUD 作業的範例程式碼。Follow the steps in this doc to install the .NET package, build an app, and try out the example code for basic CRUD operations on the data stored in Azure Cosmos DB.

Azure Cosmos DB 是 Microsoft 的快速 NoSQL 資料庫,可支援任何規模的開放式 API。Azure Cosmos DB is Microsoft’s fast NoSQL database with open APIs for any scale. 您可以使用 Azure Cosmos DB 快速地建立及查詢機碼/值、文件與圖形資料庫。You can use Azure Cosmos DB to quickly create and query key/value, document, and graph databases. 使用適用於 .NET 的 Azure Cosmos DB SQL API 用戶端程式庫來:Use the Azure Cosmos DB SQL API client library for .NET to:

  • 建立 Azure Cosmos 資料庫與容器Create an Azure Cosmos database and a container
  • 將範例資料新增至容器Add sample data to the container
  • 查詢資料Query the data
  • 刪除資料庫Delete the database

API 參考文件 | 程式庫原始程式碼 | 套件 (NuGet)API reference documentation | Library source code | Package (NuGet)

PrerequisitesPrerequisites

設定Setting up

此節將逐步引導您建立 Azure Cosmos 帳戶,並設定使用適用於 .NET 的 Azure Cosmos DB SQL API 用戶端程式庫來管理資源的專案。This section walks you through creating an Azure Cosmos account and setting up a project that uses Azure Cosmos DB SQL API client library for .NET to manage resources. 此文章中描述的範例程式碼會在該資料庫內建立 FamilyDatabase 資料庫與家庭成員 (每個家庭成員都是一個項目)。The example code described in this article creates a FamilyDatabase database and family members (each family member is an item) within that database. 每個家庭成員都有屬性,例如 Id, FamilyName, FirstName, LastName, Parents, Children, Address,Each family member has properties such as Id, FamilyName, FirstName, LastName, Parents, Children, Address,. LastName 屬性會作為容器的資料分割索引鍵使用。The LastName property is used as the partition key for the container.

建立 Azure Cosmos 帳戶Create an Azure Cosmos account

如果您使用 免費試用 Azure Cosmos DB 選項來建立 Azure Cosmos 帳戶,則必須建立類型為 SQL API 的 Azure Cosmos DB 帳戶。If you use the Try Azure Cosmos DB for free option to create an Azure Cosmos account, you must create an Azure Cosmos DB account of type SQL API. 已為您建立 Azure Cosmos DB 測試帳戶。An Azure Cosmos DB test account is already created for you. 您不需要明確建立帳戶,因此您可以略過此小節並移至下一小節。You don't have to create the account explicitly, so you can skip this section and move to the next section.

如果您有自己的 Azure 訂用帳戶,或已建立免費訂用帳戶,您應該明確地建立 Azure Cosmos 帳戶。If you have your own Azure subscription or created a subscription for free, you should create an Azure Cosmos account explicitly. 下列程式碼會建立包含工作階段一致性的 Azure Cosmos 帳戶。The following code will create an Azure Cosmos account with session consistency. 該帳戶會在 South Central USNorth Central US 中複寫。The account is replicated in South Central US and North Central US.

您可以使用 Azure Cloud Shell 來建立 Azure Cosmos 帳戶。You can use Azure Cloud Shell to create the Azure Cosmos account. Azure Cloud Shell 是可經由瀏覽器存取的已驗證互動式殼層,應用在 Azure 資源管理上。Azure Cloud Shell is an interactive, authenticated, browser-accessible shell for managing Azure resources. 它可讓您彈性地選擇最適合您工作方式的殼層體驗 (Bash 或 PowerShell)。It provides the flexibility of choosing the shell experience that best suits the way you work, either Bash or PowerShell. 在本快速入門中,選擇 [Bash] 模式。For this quickstart, choose Bash mode. Azure Cloud Shell 也需要儲存體帳戶,您可以在出現提示時建立一個。Azure Cloud Shell also requires a storage account, you can create one when prompted.

選取下列程式碼旁邊的 [試試看] 按鈕,選擇 [Bash] 模式,再選取 [建立儲存體帳戶] 並登入 Cloud Shell。Select the Try It button next to the following code, choose Bash mode select create a storage account and login to Cloud Shell. 接下來,複製下列程式碼並貼到 Azure Cloud Shelll 中執行。Next copy and paste the following code to Azure Cloud Shell and run it. Azure Cosmos 帳戶名稱必須是全域唯一的,請務必先更新 mysqlapicosmosdb 值,再執行命令。The Azure Cosmos account name must be globally unique, make sure to update the mysqlapicosmosdb value before you run the command.


# Set variables for the new SQL API account, database, and container
resourceGroupName='myResourceGroup'
location='southcentralus'

# The Azure Cosmos account name must be globally unique, make sure to update the `mysqlapicosmosdb` value before you run the command
accountName='mysqlapicosmosdb'

# Create a resource group
az group create \
    --name $resourceGroupName \
    --location $location

# Create a SQL API Cosmos DB account with session consistency and multi-region writes enabled
az cosmosdb create \
    --resource-group $resourceGroupName \
    --name $accountName \
    --kind GlobalDocumentDB \
    --locations regionName="South Central US" failoverPriority=0 --locations regionName="North Central US" failoverPriority=1 \
    --default-consistency-level "Session" \
    --enable-multiple-write-locations true

建立 Azure Cosmos 帳戶需要一些時間,一旦作業成功,您就可以看到確認輸出。The creation of the Azure Cosmos account takes a while, once the operation is successful, you can see the confirmation output. 命令順利完成之後,請登入 Azure 入口網站,並確認具有指定名稱的 Azure Cosmos 帳戶存在。After the command completes successfully, sign into the Azure portal and verify that the Azure Cosmos account with the specified name exists. 您可以在建立資源之後,關閉 [Azure Cloud Shell] 視窗。You can close the Azure Cloud Shell window after the resource is created.

建立新的 .NET 應用程式Create a new .NET app

在您慣用的編輯器或 IDE 中,建立新的 .NET 應用程式。Create a new .NET application in your preferred editor or IDE. 從您的本機電腦開啟 Windows 命令提示字元或終端機視窗。Open the Windows command prompt or a Terminal window from your local computer. 您將會從命令提示字元或終端機執行下一節中的所有命令。You will run all the commands in the next sections from the command prompt or terminal. 執行下列 dotnet new 命令來建立名稱為 todo 的新應用程式。Run the following dotnet new command to create a new app with the name todo. --langVersion 參數會設定所建立專案檔中的 LangVersion 屬性。The --langVersion parameter sets the LangVersion property in the created project file.

dotnet new console --langVersion 7.1 -n todo

將目錄變更為新建立的應用程式資料夾。Change your directory to the newly created app folder. 您可以使用下列命令來建置應用程式:You can build the application with:

cd todo
dotnet build

組建的預期輸出看起來應像這樣:The expected output from the build should look something like this:

  Restore completed in 100.37 ms for C:\Users\user1\Downloads\CosmosDB_Samples\todo\todo.csproj.
  todo -> C:\Users\user1\Downloads\CosmosDB_Samples\todo\bin\Debug\netcoreapp2.2\todo.dll
  todo -> C:\Users\user1\Downloads\CosmosDB_Samples\todo\bin\Debug\netcoreapp2.2\todo.Views.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:34.17

安裝 Azure Cosmos DB 套件Install the Azure Cosmos DB package

若您仍在應用程式目錄中,請使用 dotnet add package 命令安裝適用於 .NET Core 的 Azure Cosmos DB 用戶端程式庫。While still in the application directory, install the Azure Cosmos DB client library for .NET Core by using the dotnet add package command.

dotnet add package Microsoft.Azure.Cosmos

從 Azure 入口網站複製您的 Azure Cosmos 帳戶認證Copy your Azure Cosmos account credentials from the Azure portal

範例應用程式需要驗證您的 Azure Cosmos 帳戶。The sample application needs to authenticate to your Azure Cosmos account. 若要進行驗證,您應該將 Azure Cosmos 帳號認證傳遞給應用程式。To authenticate, you should pass the Azure Cosmos account credentials to the application. 請依照下列步驟取得您的 Azure Cosmos 帳戶認證:Get your Azure Cosmos account credentials by following these steps:

  1. 登入 Azure 入口網站Sign in to the Azure portal.

  2. 瀏覽至 Azure Cosmos 帳戶。Navigate to your Azure Cosmos account.

  3. 開啟 [金鑰] 窗格,然後複製您帳戶的 URI主索引鍵Open the Keys pane and copy the URI and PRIMARY KEY of your account. 在下一個步驟中,您會將 URI 和索引鍵值新增至環境變數。You will add the URI and keys values to an environment variable in the next step.

設定環境變數Set the environment variables

在複製您帳戶的 URI主索引鍵 後,請在執行應用程式的本機電腦上,將該字串儲存到新的環境變數中。After you have copied the URI and PRIMARY KEY of your account, save them to a new environment variable on the local machine running the application. 若要設定環境變數,請開啟主控台視窗,然後執行下列命令。To set the environment variable, open a console window, and run the following command. 請務必取代 <Your_Azure_Cosmos_account_URI><Your_Azure_Cosmos_account_PRIMARY_KEY> 值。Make sure to replace <Your_Azure_Cosmos_account_URI> and <Your_Azure_Cosmos_account_PRIMARY_KEY> values.

WindowsWindows

setx EndpointUrl "<Your_Azure_Cosmos_account_URI>"
setx PrimaryKey "<Your_Azure_Cosmos_account_PRIMARY_KEY>"

LinuxLinux

export EndpointUrl = "<Your_Azure_Cosmos_account_URI>"
export PrimaryKey = "<Your_Azure_Cosmos_account_PRIMARY_KEY>"

macOSmacOS

export EndpointUrl = "<Your_Azure_Cosmos_account_URI>"
export PrimaryKey = "<Your_Azure_Cosmos_account_PRIMARY_KEY>"

物件模型Object model

在開始建置應用程式之前,讓我們看一下 Azure Cosmos DB 中的資源階層,以及用於建立及存取這些資源的物件模型。Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB and the object model used to create and access these resources. Azure Cosmos DB 會依照下列順序建立資源:The Azure Cosmos DB creates resources in the following order:

  • Azure Cosmos 帳戶Azure Cosmos account
  • 資料庫Databases
  • 容器Containers
  • 項目Items

若要了解有關不同實體的階層,請參閱使用 Azure Cosmos DB 中的資料庫、容器和項目 (部分機器翻譯) 一文。To learn in more about the hierarchy of different entities, see the working with databases, containers, and items in Azure Cosmos DB article. 您將使用下列 .NET 類別與這些資源互動:You will use the following .NET classes to interact with these resources:

  • CosmosClient - 此類別提供適用於 Azure Cosmos DB 服務的用戶端邏輯表示法。CosmosClient - This class provides a client-side logical representation for the Azure Cosmos DB service. 用戶端物件會用於設定及執行針對服務的要求。The client object is used to configure and execute requests against the service.

  • CreateDatabaseIfNotExistsAsync - 此方法會建立 (如果不存在) 或取得 (如果已經存在) 資料庫資源作為非同步作業。CreateDatabaseIfNotExistsAsync - This method creates (if doesn't exist) or gets (if already exists) a database resource as an asynchronous operation.

  • CreateContainerIfNotExistsAsync - 此方法會建立 (如果不存在) 或取得 (如果已經存在) 容器作為非同步作業。CreateContainerIfNotExistsAsync- - This method creates (if it doesn't exist) or gets (if it already exists) a container as an asynchronous operation. 您可以檢查來自回應的狀態碼,以判斷容器是新建立的 (201) 還是傳回的現有容器 (200)。You can check the status code from the response to determine whether the container was newly created (201) or an existing container was returned (200).

  • CreateItemAsync - 此方法會在容器內建立項目。CreateItemAsync - This method creates an item within the container.

  • UpsertItemAsync - 此方法會在容器內建立項目 (如果尚未存在) 或取代項目 (如果已存在)。UpsertItemAsync - This method creates an item within the container if it doesn't already exist or replaces the item if it already exists.

  • GetItemQueryIterator - 此方法會使用具有參數化值的 SQL 陳述式,在 Azure Cosmos 資料庫中的容器下建立項目的查詢。GetItemQueryIterator - This method creates a query for items under a container in an Azure Cosmos database using a SQL statement with parameterized values.

  • DeleteAsync - 從您的 Azure Cosmos 帳戶中刪除指定的資料庫。DeleteAsync - Deletes the specified database from your Azure Cosmos account. DeleteAsync 方法只會刪除資料庫。DeleteAsync method only deletes the database. Cosmosclient 執行個體的處置應單獨進行 (這會在 DeleteDatabaseAndCleanupAsync 方法中執行)。Disposing of the Cosmosclient instance should happen separately (which it does in the DeleteDatabaseAndCleanupAsync method.

程式碼範例Code examples

此文章中描述的範例程式碼會在 Azure Cosmos DB 中建立家庭資料庫。The sample code described in this article creates a family database in Azure Cosmos DB. 家庭資料庫包含家庭詳細資料,例如姓名、地址、位置、相關聯的家長、子女和寵物。The family database contains family details such as name, address, location, the associated parents, children, and pets. 將資料填入您的 Azure Cosmos 帳戶之前,請定義家庭項目的屬性。Before populating the data to your Azure Cosmos account, define the properties of a family item. 在範例應用程式的根層級建立一個名為 Family.cs 的新類別,並在其中新增下列程式碼:Create a new class named Family.cs at the root level of your sample application and add the following code to it:

using Newtonsoft.Json;

namespace todo
{
    public class Family
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        public string LastName { get; set; }
        public Parent[] Parents { get; set; }
        public Child[] Children { get; set; }
        public Address Address { get; set; }
        public bool IsRegistered { get; set; }
        // The ToString() method is used to format the output, it's used for demo purpose only. It's not required by Azure Cosmos DB
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

    public class Parent
    {
        public string FamilyName { get; set; }
        public string FirstName { get; set; }
    }

    public class Child
    {
        public string FamilyName { get; set; }
        public string FirstName { get; set; }
        public string Gender { get; set; }
        public int Grade { get; set; }
        public Pet[] Pets { get; set; }
    }

    public class Pet
    {
        public string GivenName { get; set; }
    }

    public class Address
    {
        public string State { get; set; }
        public string County { get; set; }
        public string City { get; set; }
    }
}

新增 using 指示詞並定義用戶端物件Add the using directives & define the client object

從專案目錄中,在您的編輯器中開啟 Program.cs 檔案,並在應用程式的頂端新增下列 using 指示詞:From the project directory, open the Program.cs file in your editor and add the following using directives at the top of your application:


using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Cosmos;

Program.cs 檔案中加入程式碼,以讀取您在上一個步驟中設定的環境變數。To the Program.cs file, add code to read the environment variables that you have set in the previous step. 定義 CosmosClientDatabaseContainer 物件。Define the CosmosClient, Database, and the Container objects. 接下來,將程式碼新增至 main 方法,以呼叫您管理 Azure Cosmos 帳戶資源的 GetStartedDemoAsync 方法。Next add code to the main method that calls the GetStartedDemoAsync method where you manage Azure Cosmos account resources.

namespace todo
{
public class Program
{

    /// The Azure Cosmos DB endpoint for running this GetStarted sample.
    private string EndpointUrl = Environment.GetEnvironmentVariable("EndpointUrl");

    /// The primary key for the Azure DocumentDB account.
    private string PrimaryKey = Environment.GetEnvironmentVariable("PrimaryKey");

    // The Cosmos client instance
    private CosmosClient cosmosClient;

    // The database we will create
    private Database database;

    // The container we will create.
    private Container container;

    // The name of the database and container we will create
    private string databaseId = "FamilyDatabase";
    private string containerId = "FamilyContainer";

    public static async Task Main(string[] args)
    {
       try
       {
           Console.WriteLine("Beginning operations...\n");
           Program p = new Program();
           await p.GetStartedDemoAsync();

        }
        catch (CosmosException de)
        {
           Exception baseException = de.GetBaseException();
           Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
        }
        finally
        {
            Console.WriteLine("End of demo, press any key to exit.");
            Console.ReadKey();
        }
    }
}
}

建立資料庫Create a database

program.cs 類別內定義 CreateDatabaseAsync 方法。Define the CreateDatabaseAsync method within the program.cs class. 如果 FamilyDatabase 不存在,則此方法會建立它。This method creates the FamilyDatabase if it doesn't already exist.

private async Task CreateDatabaseAsync()
{
    // Create a new database
    this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
    Console.WriteLine("Created Database: {0}\n", this.database.Id);
}

建立容器Create a container

program.cs 類別內定義 CreateContainerAsync 方法。Define the CreateContainerAsync method within the program.cs class. 如果 FamilyContainer 不存在,則此方法會建立它。This method creates the FamilyContainer if it doesn't already exist.

/// Create the container if it does not exist. 
/// Specifiy "/LastName" as the partition key since we're storing family information, to ensure good distribution of requests and storage.
private async Task CreateContainerAsync()
{
    // Create a new container
    this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName");
    Console.WriteLine("Created Container: {0}\n", this.container.Id);
}

建立項目Create an item

透過使用下列程式碼新增 AddItemsToContainerAsync 方法來建立家庭項目。Create a family item by adding the AddItemsToContainerAsync method with the following code. 您可以使用 CreateItemAsyncUpsertItemAsync 方法來建立項目:You can use the CreateItemAsync or UpsertItemAsync methods to create an item:

private async Task AddItemsToContainerAsync()
{
    // Create a family object for the Andersen family
    Family andersenFamily = new Family
    {
        Id = "Andersen.1",
        LastName = "Andersen",
        Parents = new Parent[]
        {
           new Parent { FirstName = "Thomas" },
           new Parent { FirstName = "Mary Kay" }
        },
        Children = new Child[]
        {
           new Child
            {
                FirstName = "Henriette Thaulow",
                Gender = "female",
                Grade = 5,
                Pets = new Pet[]
                {
                    new Pet { GivenName = "Fluffy" }
                }
            }
        },
        Address = new Address { State = "WA", County = "King", City = "Seattle" },
        IsRegistered = false
    };

    try
    {
        // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen".
        ItemResponse<Family> andersenFamilyResponse = await this.container.CreateItemAsync<Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));
        // Note that after creating the item, we can access the body of the item with the Resource property of the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
        Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", andersenFamilyResponse.Resource.Id, andersenFamilyResponse.RequestCharge);
    }
    catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
    {
        Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamily.Id);                
    }
}

查詢項目Query the items

插入項目之後,您可以執行查詢以取得 "Andersen" 家庭的詳細資料。After inserting an item, you can run a query to get the details of "Andersen" family. 下列程式碼顯示如何直接使用 SQL 查詢來執行查詢。The following code shows how to execute the query using the SQL query directly. 取得 "Andersen" 家庭詳細資料的 SQL 查詢是:SELECT * FROM c WHERE c.LastName = 'Andersen'The SQL query to get the "Anderson" family details is: SELECT * FROM c WHERE c.LastName = 'Andersen'. program.cs 類別中定義 QueryItemsAsync 方法,並在其中加入下列程式碼:Define the QueryItemsAsync method within the program.cs class and add the following code to it:

private async Task QueryItemsAsync()
{
    var sqlQueryText = "SELECT * FROM c WHERE c.LastName = 'Andersen'";

    Console.WriteLine("Running query: {0}\n", sqlQueryText);

    QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
    FeedIterator<Family> queryResultSetIterator = this.container.GetItemQueryIterator<Family>(queryDefinition);

    List<Family> families = new List<Family>();

    while (queryResultSetIterator.HasMoreResults)
    {
        FeedResponse<Family> currentResultSet = await queryResultSetIterator.ReadNextAsync();
        foreach (Family family in currentResultSet)
        {
            families.Add(family);
            Console.WriteLine("\tRead {0}\n", family);
        }
    }
}

刪除資料庫Delete the database

最後,您可以使用下列程式碼來刪除新增 DeleteDatabaseAndCleanupAsync 方法的資料庫:Finally you can delete the database adding the DeleteDatabaseAndCleanupAsync method with the following code:

private async Task DeleteDatabaseAndCleanupAsync()
{
   DatabaseResponse databaseResourceResponse = await this.database.DeleteAsync();
   // Also valid: await this.cosmosClient.Databases["FamilyDatabase"].DeleteAsync();

   Console.WriteLine("Deleted Database: {0}\n", this.databaseId);

   //Dispose of CosmosClient
    this.cosmosClient.Dispose();
}

執行 CRUD 作業Execute the CRUD operations

定義所有必要的方法之後,使用 GetStartedDemoAsync 方法來執行它們。After you have defined all the required methods, execute them with in the GetStartedDemoAsync method. DeleteDatabaseAndCleanupAsync 方法在此程式碼中已取消註解,因為如果執行該方法,您將不會看到任何資源。The DeleteDatabaseAndCleanupAsync method commented out in this code because you will not see any resources if that method is executed. 驗證您的 Azure Cosmos DB 資源已在 Azure 入口網站中建立之後,您可以將它取消註解。You can uncomment it after validating that your Azure Cosmos DB resources were created in the Azure portal.

public async Task GetStartedDemoAsync()
{
    // Create a new instance of the Cosmos Client
    this.cosmosClient = new CosmosClient(EndpointUrl, PrimaryKey);
    await this.CreateDatabaseAsync();
    await this.CreateContainerAsync();
    await this.AddItemsToContainerAsync();
    await this.QueryItemsAsync();
}

新增所有必要的方法之後,請儲存 Program.cs 檔案。After you add all the required methods, save the Program.cs file.

執行程式碼Run the code

接下來建置並執行應用程式,以建立 Azure Cosmos DB 資源。Next build and run the application to create the Azure Cosmos DB resources. 請務必開啟一個新的命令提示字元視窗,不要使用您用來設定環境變數的相同執行個體。Make sure to open a new command prompt window, don't use the same instance that you have used to set the environment variables. 因為環境變數未在目前開啟的視窗中設定。Because the environment variables are not set in the current open window. 您需要開啟新的命令提示字元才能看到更新。You will need to open a new command prompt to see the updates.

dotnet build
dotnet run

執行應用程式時會產生下列輸出。The following output is generated when you run the application. 您也可以登入 Azure 入口網站並驗證是否已建立資源:You can also sign into the Azure portal and validate that the resources are created:

Created Database: FamilyDatabase

Created Container: FamilyContainer

Created item in database with id: Andersen.1 Operation consumed 11.62 RUs.

Running query: SELECT * FROM c WHERE c.LastName = 'Andersen'

        Read {"id":"Andersen.1","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null,"FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":5,"Pets":[{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":false}

End of demo, press any key to exit.

您可以透過登入 Azure 入口網站並查看 Azure Cosmos 帳戶中的必要項目,來驗證是否已建立資料。You can validate that the data is created by signing into the Azure portal and see the required items in your Azure Cosmos account.

清除資源Clean up resources

若不再需要,您可以使用 Azure CLI 或 Azure PowerShell 移除 Azure Cosmos 帳戶與對應的資源群組。When no longer needed, you can use the Azure CLI or Azure PowerShell to remove the Azure Cosmos account and the corresponding resource group. 下列命令說明如何使用 Azure CLI 刪除資源群組:The following command shows how to delete the resource group by using the Azure CLI:

az group delete -g "myResourceGroup"

後續步驟Next steps

在此快速入門中,您已了解如何建立 Azure Cosmos 帳戶、使用 .NET Core 應用程式建立資料庫與容器。In this quickstart, you learned how to create an Azure Cosmos account, create a database and a container using a .NET Core app. 您現在可以使用下列文章中的指示,將其他資料匯入到您的 Azure Cosmos 帳戶。You can now import additional data to your Azure Cosmos account with the instructions int the following article.