透過 .NET SDK 開始使用 Azure Cosmos DB 資料表 API 和 Azure 資料表儲存體Get started with Azure Cosmos DB Table API and Azure Table storage using the .NET SDK

提示

本文中的內容適用於 Azure 資料表儲存體和 Azure Cosmos DB 資料表 API。The content in this article applies to Azure Table storage and the Azure Cosmos DB Table API. Azure Cosmos DB 資料表 API 是資料表儲存體的進階供應項目,可提供輸送量最佳化的資料表、全域發佈,以及自動次要索引。The Azure Cosmos DB Table API is a premium offering for table storage that offers throughput-optimized tables, global distribution, and automatic secondary indexes.

您可以使用 Azure Cosmos DB 資料表 API 或 Azure 資料表儲存體,來將結構化 NoSQL 資料儲存於雲端,為索引鍵/屬性存放區提供無結構描述的設計。You can use the Azure Cosmos DB Table API or Azure Table storage to store structured NoSQL data in the cloud, providing a key/attribute store with a schema less design. 由於 Azure Cosmos DB 資料表 API 和資料表儲存體均無結構描述,因此可輕易地隨著應用程式發展需求來調整資料。Because Azure Cosmos DB Table API and Table storage are schema less, it's easy to adapt your data as the needs of your application evolve. 您可以使用 Azure Cosmos DB 資料表 API 或資料表儲存體來儲存具彈性的資料集,例如,Web 應用程式的使用者資料、通訊錄、裝置資訊,或服務所需的其他中繼資料類型。You can use Azure Cosmos DB Table API or the Table storage to store flexible datasets such as user data for web applications, address books, device information, or other types of metadata your service requires.

本教學課程所述的範例將示範如何搭配 Azure Cosmo DB 資料表 API 和 Azure 資料表儲存體案例,來使用適用於 .NET 的 Microsoft Azure Cosmos DB 資料表程式庫 (英文)。This tutorial describes a sample that shows you how to use the Microsoft Azure Cosmos DB Table Library for .NET with Azure Cosmo DB Table API and Azure Table storage scenarios. 您必須使用 Azure 服務特定的連線。You must use the connection specific to the Azure service. 這些案例均會使用 C# 範例來探索,說明如何建立資料表、插入/更新資料、查詢資料,以及刪除資料表。These scenarios are explored using C# examples that illustrate how to create tables, insert/ update data, query data and delete the tables.

必要條件Prerequisites

您需要下列項目才能成功完成此範例︰You need the following to complete this sample successfully:

建立 Azure Cosmos DB 表格 API 帳戶Create an Azure Cosmos DB Table API account

  1. 在新的瀏覽器視窗中,登入 Azure 入口網站In a new browser window, sign in to the Azure portal.

  2. 在左側導覽窗格中,選取 [建立資源] 。In the left navigation pane, select Create a resource. 選取 [資料庫] ,然後選取 [Azure Cosmos DB] 。Select Databases and then select Azure Cosmos DB.

    Azure 入口網站的螢幕擷取畫面,其中反白顯示 [其他服務] 和 Azure Cosmos DB

  3. 在 [建立 Azure Cosmos DB 帳戶] 頁面上,輸入新 Azure Cosmos DB 帳戶的設定:On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account:

    設定Setting Value 說明Description
    訂用帳戶Subscription 您的訂用帳戶Your subscription 選取要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    資源群組Resource Group 新建Create new

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource group name for your account. 為求簡化,請使用和識別碼相同的名稱。For simplicity, use the same name as your ID.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入唯一名稱來識別您的 Azure Cosmos DB 帳戶。Enter a unique name to identify your Azure Cosmos DB account.

    識別碼只能使用小寫字母、數字及連字號 (-) 字元。The ID can use only lowercase letters, numbers, and the hyphen (-) character. 其長度必須介於 3 到 31 個字元之間。It must be between 3 and 31 characters long.
    APIAPI Azure 資料表Azure Table API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core(SQL) (適用於文件資料庫)、Gremlin (適用於圖形資料庫)、MongoDB (適用於文件資料庫)、「Azure 資料表」及 Cassandra。Azure Cosmos DB provides five APIs: Core(SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [Azure 資料表] ,因為在本快速入門中,您會建立可搭配資料表 API 使用的資料表。Select Azure Table because in this quickstart you're creating a table that works with the Table API.

    深入了解資料表 APILearn more about the Table API.
    位置Location 選取最接近使用者的區域Select the region closest to your users 選取用來裝載 Azure Cosmos DB 帳戶的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用最接近使用者的位置,讓他們能以最快速度存取資料。Use the location that's closest to your users to give them the fastest access to data.

    您可以保留 [異地備援] 和 [多重區域寫入] 選項的預設值 ([停用] ) 以避免產生額外的 RU 費用。You can leave the Geo-Redundancy and Multi-region Writes options at their default values (Disable) to avoid additional RU charges. 您可以略過 [網路] 和 [標記] 區段。You can skip the Network and Tags sections.

  4. 請選取 [檢閱 + 建立] 。Select Review+Create. 驗證完成之後,請選取 [建立] 來建立帳戶。After the validation is complete, select Create to create the account.

    Azure Cosmos DB 的新帳戶頁面

  5. 建立帳戶需要幾分鐘的時間。It takes a few minutes to create the account. 您將會看到一個訊息,指出 [您的部署正在進行] 。You'll see a message that states Your deployment is underway. 等待部署完成,然後選取 [前往資源] 。Wait for the deployment to finish and then select Go to resource.

    Azure 入口網站的 [通知] 窗格

建立 .NET 主控台專案Create a .NET console project

在 Visual Studio 中,建立新的 .NET 主控台應用程式。In Visual Studio, create a new .NET console application. 下列步驟說明如何在 Visual Studio 2019 中建立主控台應用程式。The following steps show you how to create a console application in Visual Studio 2019. 您可以在任何類型的 .NET 應用程式 (包括 Azure 雲端服務或 Web 應用程式,以及桌面與行動應用程式) 中使用 Azure CosmosDB 資料表程式庫。You can use the Azure Cosmos DB Table Library in any type of .NET application, including an Azure cloud service or web app, and desktop and mobile applications. 在本指南中,為求簡化,我們會使用主控台應用程式。In this guide, we use a console application for simplicity.

  1. 選取 [檔案] > [新增] > [專案] 。Select File > New > Project.

  2. 選擇 [主控台應用程式 (.NET Core)] ,然後選取 [下一步] 。Choose Console App (.NET Core), and then select Next.

  3. 在 [專案名稱] 欄位中輸入應用程式的名稱,例如 CosmosTableSamplesIn the Project name field, enter a name for your application, such as CosmosTableSamples. (您可以視需要提供不同的名稱。)(You can provide a different name as needed.)

  4. 選取 [建立] 。Select Create.

此範例中的所有程式碼範例均可新增至主控台應用程式 Program.cs 檔案的 Main() 方法。All code examples in this sample can be added to the Main() method of your console application's Program.cs file.

安裝必要的 NuGet 套件Install the required NuGet package

若要取得 NuGet 套件,請遵循下列步驟:To obtain the NuGet package, follow these steps:

  1. 在 [方案總管] 中以滑鼠右鍵按一下專案,然後選擇 [管理 NuGet 封裝] 。Right-click your project in Solution Explorer and choose Manage NuGet Packages.

  2. 線上搜尋 Microsoft.Azure.Cosmos.TableMicrosoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.JsonMicrosoft.Extensions.Configuration.Binder,然後選取 [安裝] 以安裝 Microsoft Azure CosmosDB 資料表程式庫。Search online for Microsoft.Azure.Cosmos.Table, Microsoft.Extensions.Configuration, Microsoft.Extensions.Configuration.Json, Microsoft.Extensions.Configuration.Binder and select Install to install the Microsoft Azure Cosmos DB Table Library.

設定儲存體連接字串Configure your storage connection string

  1. Azure 入口網站中,瀏覽至您的 Azure Cosmos 帳戶或資料表儲存體帳戶。From the Azure portal, navigate to your Azure Cosmos account or the Table Storage account.

  2. 開啟 [連接字串] 或 [存取金鑰] 窗格。Open the Connection String or Access keys pane. 使用視窗右方的複製按鈕來複製主要連接字串Use the copy button on the right side of the window to copy the PRIMARY CONNECTION STRING.

    在 [連接字串] 窗格中檢視及複製主要連接字串

  3. 若要設定連接字串,從 Visual Studio 中,以滑鼠右鍵按一下您的專案 CosmosTableSamplesTo configure your connection string, from visual studio right click on your project CosmosTableSamples.

  4. 選取 [新增] ,然後選取 [新增項目] 。Select Add and then New Item. 建立檔案類型為 TypeScript JSON 組態檔的新檔案 Settings.jsonCreate a new file Settings.json with file type as TypeScript JSON Configuration File.

  5. 將 Settings.json 檔案中的程式碼取代為下列程式碼,並指派您的主要連接字串:Replace the code in Settings.json file with the following code and assign your primary connection string:

    {
    "StorageConnectionString": <Primary connection string of your Azure Cosmos DB account>
    }
    
  6. 以滑鼠右鍵按一下您的專案 CosmosTableSamplesRight click on your project CosmosTableSamples. 選取 [新增] 、[新增項目] ,然後新增名為 AppSettings.cs 的類別。Select Add, New Item and add a class named AppSettings.cs.

  7. 將下列程式碼新增至 AppSettings.cs 檔案。Add the following code to the AppSettings.cs file. 此檔案會從 Settings.json 檔案中讀取連接字串,並將它指派給設定參數:This file reads the connection string from Settings.json file and assigns it to the configuration parameter:

    namespace CosmosTableSamples
    {
     using Microsoft.Extensions.Configuration;
     public class AppSettings
     {
         public string StorageConnectionString { get; set; }
         public static AppSettings LoadAppSettings()
         {
             IConfigurationRoot configRoot = new ConfigurationBuilder()
                 .AddJsonFile("Settings.json")
                 .Build();
             AppSettings appSettings = configRoot.Get<AppSettings>();
             return appSettings;
         }
     }
    }
    

剖析及驗證連線詳細資料Parse and validate the connection details

  1. 以滑鼠右鍵按一下您的專案 CosmosTableSamplesRight click on your project CosmosTableSamples. 選取 [新增] 、[新增項目] ,然後新增名為 Common.cs 的類別。Select Add, New Item and add a class named Common.cs. 您將撰寫程式碼來驗證連線詳細資料,並在此類別內建立資料表。You will write code to validate the connection details and create a table within this class.

  2. 定義 CreateStorageAccountFromConnectionString 方法,如下所示。Define a method CreateStorageAccountFromConnectionString as shown below. 此方法將剖析連接字串詳細資料,並驗證 "Settings.json" 檔案中所提供的帳戶名稱和帳戶金鑰詳細資料為有效的。This method will parse the connection string details and validate that the account name and account key details provided in the "Settings.json" file are valid.

using System;

namespace CosmosTableSamples
{
   using System.Threading.Tasks;
   using Microsoft.Azure.Cosmos.Table;
   using Microsoft.Azure.Documents;

   public class Common
   {
       public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)
       {
           CloudStorageAccount storageAccount;
           try
           {
               storageAccount = CloudStorageAccount.Parse(storageConnectionString);
           }
           catch (FormatException)
           {
               Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the application.");
               throw;
           }
           catch (ArgumentException)
           {
               Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
               Console.ReadLine();
               throw;
           }

           return storageAccount;
       }
   }
}

建立資料表Create a Table

CloudTableClient 類別可讓您擷取表格儲存體中儲存的資料表。The CloudTableClient class enables you to retrieve tables and entities stored in Table storage. 因為我們在 Cosmos DB 資料表 API 帳戶中沒有任何資料表,讓我們在 Common.cs 類別中新增 CreateTableAsync 方法來建立資料表:Because we don’t have any tables in the Cosmos DB Table API account, let’s add the CreateTableAsync method to the Common.cs class to create a table:

public static async Task<CloudTable> CreateTableAsync(string tableName)
  {
    string storageConnectionString = AppSettings.LoadAppSettings().StorageConnectionString;

    // Retrieve storage account information from connection string.
    CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString);

    // Create a table client for interacting with the table service
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());

    Console.WriteLine("Create a Table for the demo");

    // Create a table client for interacting with the table service 
    CloudTable table = tableClient.GetTableReference(tableName);
    if (await table.CreateIfNotExistsAsync())
    {
      Console.WriteLine("Created Table named: {0}", tableName);
    }
    else
    {
      Console.WriteLine("Table {0} already exists", tableName);
    }

    Console.WriteLine();
    return table;
}

定義實體Define the entity

使用衍生自 TableEntity的自訂類別,將實體對應至 C# 物件。Entities map to C# objects by using a custom class derived from TableEntity. 若要將實體新增至資料表,請建立一個類別來定義實體的屬性。To add an entity to a table, create a class that defines the properties of your entity.

以滑鼠右鍵按一下您的專案 CosmosTableSamplesRight click on your project CosmosTableSamples. 選取 [新增] 、[新增資料夾] ,然後將其命名為 ModelSelect Add, New Folder and name it as Model. 在 [Model] 資料夾內新增一個名為 CustomerEntity.cs 的類別,然後將下列程式碼新增至其中。Within the Model folder add a class named CustomerEntity.cs and add the following code to it.

namespace CosmosTableSamples.Model
{
    using Microsoft.Azure.Cosmos.Table;
    public class CustomerEntity : TableEntity
    {
        public CustomerEntity()
        {
        }

        public CustomerEntity(string lastName, string firstName)
        {
            PartitionKey = lastName;
            RowKey = firstName;
        }

        public string Email { get; set; }
        public string PhoneNumber { get; set; }
    }
}

此程式碼會定義一個實體類別,使用客戶名字作為資料列索引鍵,並使用姓氏作為分割區索引鍵。This code defines an entity class that uses the customer's first name as the row key and last name as the partition key. 系統會在資料表中以實體的資料分割和資料列索引鍵共同針對實體進行唯一識別。Together, an entity's partition and row key uniquely identify it in the table. 查詢具有相同分割區索引鍵的實體,其速度快於查詢具有不同分割區索引鍵的實體,但使用不同的分割區索引鍵可針對平行作業提供更佳的延展性。Entities with the same partition key can be queried faster than entities with different partition keys but using diverse partition keys allows for greater scalability of parallel operations. 若要將實體儲存於資料表,其必須屬於支援的類型,例如衍生自 TableEntity 類別。Entities to be stored in tables must be of a supported type, for example derived from the TableEntity class. 您想要儲存在資料表中的實體屬性必須是該類型的公用屬性,而且同時支援值的取得和設定。Entity properties you'd like to store in a table must be public properties of the type, and support both getting and setting of values. 此外,您的實體類型必須公開無參數建構函式。Also, your entity type must expose a parameter-less constructor.

插入或合併實體Insert or merge an entity

下列程式碼範例會建立實體物件,並將它新增至資料表。The following code example creates an entity object and adds it to the table. TableOperation (英文) 類別內的 InsertOrMerge 方法可用來插入或合併實體。The InsertOrMerge method within the TableOperation class is used to insert or merge an entity. 呼叫 CloudTable.ExecuteAsync (英文) 方法來執行作業。The CloudTable.ExecuteAsync method is called to execute the operation.

以滑鼠右鍵按一下您的專案 CosmosTableSamplesRight click on your project CosmosTableSamples. 選取 [新增] 、[新增項目] ,然後新增名為 SamplesUtils.cs 的類別。Select Add, New Item and add a class named SamplesUtils.cs. 此類別會儲存在實體上執行 CRUD 作業所需的所有程式碼。This class stores all the code required to perform CRUD operations on the entities.

 public static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
 {
     if (entity == null)
     {
         throw new ArgumentNullException("entity");
     }
     try
     {
         // Create the InsertOrReplace table operation
         TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

         // Execute the operation.
         TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
         CustomerEntity insertedCustomer = result.Result as CustomerEntity;

         // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure Cosmos DB
         if (result.RequestCharge.HasValue)
         {
             Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
         }

         return insertedCustomer;
     }
     catch (StorageException e)
     {
         Console.WriteLine(e.Message);
         Console.ReadLine();
         throw;
     }
 }

從分割區取得實體Get an entity from a partition

您也可以使用 TableOperation (英文) 類別下方的 Retrieve 方法,從分割區取得實體。You can get entity from a partition by using the Retrieve method under the TableOperation class. 下列程式碼範例會取得分割區索引鍵的資料列索引鍵、客戶實體的電子郵件及電話號碼。The following code example gets the partition key row key, email and phone number of a customer entity. 此範例也會列印出查詢實體所耗用的要求單位。This example also prints out the request units consumed to query for the entity. 若要查詢實體,將下列程式碼附加至 SamplesUtils.cs 檔案:To query for an entity, append the following code to SamplesUtils.cs file:

public static async Task<CustomerEntity> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
    {
      try
      {
        TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(partitionKey, rowKey);
        TableResult result = await table.ExecuteAsync(retrieveOperation);
        CustomerEntity customer = result.Result as CustomerEntity;
        if (customer != null)
        {
          Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
        }

        // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB 
        if (result.RequestCharge.HasValue)
        {
           Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
        }

        return customer;
        }
        catch (StorageException e)
        {
           Console.WriteLine(e.Message);
           Console.ReadLine();
           throw;
        }
    }

刪除實體Delete an entity

使用更新實體時所展示的相同方法,輕鬆地在擷取實體後將其刪除。You can easily delete an entity after you have retrieved it by using the same pattern shown for updating an entity. 下列程式碼會擷取並刪除客戶實體。The following code retrieves and deletes a customer entity. 若要刪除實體,將下列程式碼附加至 SamplesUtils.cs 檔案:To delete an entity, append the following code to SamplesUtils.cs file:

public static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
   {
     try
     {
        if (deleteEntity == null)
     {
        throw new ArgumentNullException("deleteEntity");
     }

    TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
    TableResult result = await table.ExecuteAsync(deleteOperation);

    // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB 
    if (result.RequestCharge.HasValue)
    {
       Console.WriteLine("Request Charge of Delete Operation: " + result.RequestCharge);
    }

    }
    catch (StorageException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

針對範例資料執行 CRUD 作業Execute the CRUD operations on sample data

當您定義方法來建立資料表、插入或合併實體之後,請針對範例資料執行這些方法。After you define the methods to create table, insert or merge entities, run these methods on the sample data. 若要執行此動作,以滑鼠右鍵按一下您的專案 CosmosTableSamplesTo do so, right click on your project CosmosTableSamples. 選取 [新增] 、[新增項目] ,然後新增名為 BasicSamples.cs 的類別,並將下列程式碼新增至其中。Select Add, New Item and add a class named BasicSamples.cs and add the following code to it. 此程式碼會建立資料表並將實體新增至其中。This code creates a table, adds entities to it. 如果您想要在專案結束時刪除實體和資料表,請從下列程式碼中移除 table.DeleteIfExistsAsync()SamplesUtils.DeleteEntityAsync(table, customer) 方法的註解:If you wish to delete the entity and table at the end of the project remove the comments from table.DeleteIfExistsAsync() and SamplesUtils.DeleteEntityAsync(table, customer) methods from the following code:

using System;
namespace CosmosTableSamples
{
    using System.Threading.Tasks;
    using Microsoft.Azure.Cosmos.Table;
    using Model;

    class BasicSamples
    {
        public async Task RunSamples()
        {
            Console.WriteLine("Azure Cosmos DB Table - Basic Samples\n");
            Console.WriteLine();

            string tableName = "demo" + Guid.NewGuid().ToString().Substring(0, 5);

            // Create or reference an existing table
            CloudTable table = await Common.CreateTableAsync(tableName);

            try
            {
                // Demonstrate basic CRUD functionality 
                await BasicDataOperationsAsync(table);
            }
            finally
            {
                // Delete the table
                // await table.DeleteIfExistsAsync();
            }
        }

        private static async Task BasicDataOperationsAsync(CloudTable table)
        {
            // Create an instance of a customer entity. See the Model\CustomerEntity.cs for a description of the entity.
            CustomerEntity customer = new CustomerEntity("Harp", "Walter")
            {
                Email = "Walter@contoso.com",
                PhoneNumber = "425-555-0101"
            };

            // Demonstrate how to insert the entity
            Console.WriteLine("Insert an Entity.");
            customer = await SamplesUtils.InsertOrMergeEntityAsync(table, customer);

            // Demonstrate how to Update the entity by changing the phone number
            Console.WriteLine("Update an existing Entity using the InsertOrMerge Upsert Operation.");
            customer.PhoneNumber = "425-555-0105";
            await SamplesUtils.InsertOrMergeEntityAsync(table, customer);
            Console.WriteLine();

            // Demonstrate how to Read the updated entity using a point query 
            Console.WriteLine("Reading the updated Entity.");
            customer = await SamplesUtils.RetrieveEntityUsingPointQueryAsync(table, "Harp", "Walter");
            Console.WriteLine();

            // Demonstrate how to Delete an entity
            //Console.WriteLine("Delete the entity. ");
            //await SamplesUtils.DeleteEntityAsync(table, customer);
            //Console.WriteLine();
        }
    }
}

上述程式碼會建立以 "demo" 開頭的資料表,並將產生的 GUID 附加至資料表名稱。The previous code creates a table that starts with “demo” and the generated GUID is appended to the table name. 它接著會使用名字和姓氏 "Harp Walter" 新增客戶實體,並於稍後更新此使用者的電話號碼。It then adds a customer entity with first and last name as “Harp Walter” and later updates the phone number of this user.

在本教學課程中,您會建置程式碼,針對儲存於資料表 API 帳戶的資料執行基本的 CRUD 作業。In this tutorial, you built code to perform basic CRUD operations on the data stored in Table API account. 您也可以執行進階作業,例如,批次插入資料、查詢分割區內的所有資料、查詢分割區內某個範圍的資料、在名稱開頭為指定前置詞的帳戶中列出資料表。You can also perform advanced operations such as – batch inserting data, query all the data within a partition, query a range of data within a partition, Lists tables in the account whose names begin with the specified prefix. 您可以從 azure-cosmos-table-dotnet-core-getting-started (英文) GitHub 存放庫下載完整的範例。You can download the complete sample form azure-cosmos-table-dotnet-core-getting-started GitHub repository. AdvancedSamples.cs 類別具有更多您可針對資料執行的作業。The AdvancedSamples.cs class has more operations that you can perform on the data.

執行專案Run the project

從您的專案 CosmosTableSamplesFrom your project CosmosTableSamples. 開啟名為 Program.cs 的類別,並在其中新增下列程式碼,以便在專案執行時呼叫 BasicSamples。Open the class named Program.cs and add the following code to it for calling BasicSamples when the project runs.

using System;

namespace CosmosTableSamples
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Azure Cosmos Table Samples");
            BasicSamples basicSamples = new BasicSamples();
            basicSamples.RunSamples().Wait();
           
            Console.WriteLine();
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
    }
}

立即建置解決方案,然後按 F5 執行專案。Now build the solution and press F5 to run the project. 執行專案時,您將在命令提示字元中看見下列輸出:When the project is run, you will see the following output in the command prompt:

來自命令提示字元的輸出

如果您收到錯誤,指出執行專案時找不到 Settings.json 檔案,您可以將下列 XML 項目新增至專案設定來解決該問題。If you receive an error that says Settings.json file can’t be found when running the project, you can resolve it by adding the following XML entry to the project settings. 以滑鼠右鍵按一下 [CosmosTableSamples]、選取 [編輯 CosmosTableSamples.csproj],然後新增下列 itemGroup:Right click on CosmosTableSamples, select Edit CosmosTableSamples.csproj and add the following itemGroup:

  <ItemGroup>
    <None Update="Settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

現在您可以登入 Azure 入口網站,並確認資料存在於資料表中。Now you can sign into the Azure portal and verify that the data exists in the table.

入口網站中的結果

後續步驟Next steps

您現在可以繼續進行下一個教學課程,以了解如何將資料合併至 Azure Cosmos DB 資料表 API 帳戶。You can now proceed to the next tutorial and learn how to migrate data to Azure Cosmos DB Table API account.