快速入门:使用 .NET SDK 和 Azure Cosmos DB 生成表 API 应用Quickstart: Build a Table API app with .NET SDK and Azure Cosmos DB

适用于: 表 API

本快速入门介绍如何使用 .NET 和 Azure Cosmos DB 表 API,通过克隆 GitHub 中的示例来生成应用。This quickstart shows how to use .NET and the Azure Cosmos DB Table API to build an app by cloning an example from GitHub. 此外,本快速入门还介绍了如何创建 Azure Cosmos DB 帐户,以及如何在基于 Web 的 Azure 门户中使用数据资源管理器创建表和实体。This quickstart also shows you how to create an Azure Cosmos DB account and how to use Data Explorer to create tables and entities in the web-based Azure portal.


如果尚未安装 Visual Studio 2019,可以下载并使用 免费Visual Studio 2019 Community EditionIf you don't already have Visual Studio 2019 installed, you can download and use the free Visual Studio 2019 Community Edition. 在安装 Visual Studio 的过程中,请确保启用“Azure 开发”。Make sure that you enable Azure development during the Visual Studio setup.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

创建数据库帐户Create a database account

  1. 在新浏览器窗口中,登录到 Azure 门户In a new browser window, sign in to the Azure portal.

  2. 在左侧菜单中,选择“创建资源”。In the left menu, select Create a resource.

    在 Azure 门户中创建资源

  3. 在“新建”页上,选择“数据库” > “Azure Cosmos DB”。 On the New page, select Databases > Azure Cosmos DB.

    Azure 门户“数据库”窗格

  4. 在“创建 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 Account Name 选择“新建”。Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,请使用与 Azure Cosmos DB 帐户名称相同的名称。For simplicity, use the same name as your Azure Cosmos DB account name.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos DB 帐户的唯一名称。Enter a unique name to identify your Azure Cosmos DB account.

    帐户名称只能使用小写字母、数字及连字符 (-),必须为 3 到 31 个字符长。The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    APIAPI 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 创建单独的帐户。You must create a separate account for each API.

    选择“Azure 表”,因为在本快速入门中,将创建一个使用表 API 的表。Select Azure Table, because in this quickstart you are creating a table that works with the Table API.

    详细了解表 APILearn more about the Table API.
    位置Location 离用户最近的区域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 the data.

    可以将“异地冗余”和“多区域写入”选项保留为“禁用”,避免产生额外的费用,并跳过“网络”和“标记”部分 。 You can leave the Geo-Redundancy and Multi-region Writes options at Disable to avoid additional charges, and skip the Network and Tags sections.

  5. 选择“查看 + 创建”。Select Review+Create. 完成验证后,选择“创建”以创建帐户。After the validation is complete, select Create to create the account.

    Azure Cosmos DB 的“新建帐户”页面

  6. 创建帐户需要几分钟时间。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 门户“通知”窗格

添加表Add a table

现在可以在 Azure 门户中使用数据资源管理器工具来创建数据库和表。You can now use the Data Explorer tool in the Azure portal to create a database and table.

  1. 依次选择“数据资源管理器” > “新建表” 。Select Data Explorer > New Table.

    此时,最右侧将显示“添加表” 区域,可能需要向右滚动才能看到。The Add Table area is displayed on the far right, you may need to scroll right to see it.

    Azure 门户中的数据资源管理器

  2. 在“添加表” 页上,输入新表的设置。In the Add Table page, enter the settings for the new table.

    设置Setting 建议的值Suggested value 说明Description
    表 IDTable Id sample-tablesample-table 新表的 ID。The ID for your new table. 表名称与数据库 ID 的字符要求相同。Table names have the same character requirements as database ids. 数据库名称的长度必须为 1 到 255 个字符,不能包含 / \ # ? 或尾随空格。Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    吞吐量Throughput 400 RU400 RUs 将吞吐量更改为每秒 400 个请求单位 (RU/s)。Change the throughput to 400 request units per second (RU/s). 如果想要减少延迟,以后可以增加吞吐量。If you want to reduce latency, you can scale up the throughput later.
  3. 选择“确定” 。Select OK.

  4. 数据资源管理器将显示新的数据库和表。Data Explorer displays the new database and table.

    显示新的数据库和集合的 Azure 门户数据资源管理器

添加示例数据Add sample data

现在可以使用数据资源管理器将数据添加到新表。You can now add data to your new table using Data Explorer.

  1. 在数据资源管理器中,展开 sample-table,选择“实体”,然后选择“添加实体”。 In Data Explorer, expand sample-table, select Entities, and then select Add Entity.

    在 Azure 门户的数据资源管理器中创建新实体

  2. 现在请将数据添加到 PartitionKey 值框和 RowKey 值框,然后选择“添加实体”。 Now add data to the PartitionKey value box and RowKey value box, and select Add Entity.


    现在可以在数据资源管理器中将更多实体添加到表、编辑实体或查询数据。You can now add more entities to your table, edit your entities, or query your data in Data Explorer. 使用数据资源管理器还可以缩放吞吐量,并将存储过程、用户定义的函数和触发器添加到表中。Data Explorer is also where you can scale your throughput and add stored procedures, user-defined functions, and triggers to your table.

克隆示例应用程序Clone the sample application

现在让我们从 GitHub 克隆表应用,设置连接字符串,然后运行该应用。Now let's clone a Table app from GitHub, set the connection string, and run it. 会看到以编程方式处理数据是多么容易。You'll see how easy it is to work with data programmatically.

  1. 打开命令提示符,新建一个名为“git-samples”的文件夹,然后关闭命令提示符。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
  3. 运行下列命令以克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-table-dotnet-core-getting-started.git


有关类似代码的更详细演练,请参阅 Cosmos DB 表 API 示例一文。For a more detailed walkthrough of similar code, see the Cosmos DB Table API sample article.

在 Visual Studio 中打开示例应用程序Open the sample application in Visual Studio

  1. 在 Visual Studio 的“文件”菜单中选择“打开”,然后选择“项目/解决方案”。 In Visual Studio, from the File menu, choose Open , then choose Project/Solution.


  2. 导航到示例应用程序所克隆到的文件夹,然后打开 TableStorage.sln 文件。Navigate to the folder where you cloned the sample application and open the TableStorage.sln file.

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解如何使用代码创建数据库资源,可以查看以下代码片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 否则,可以直接跳转到本文档的更新连接字符串部分。Otherwise, you can skip ahead to update the connection string section of this doc.

  • 下面的代码演示如何在 Azure 存储中创建表:The following code shows how to create a table within the Azure Storage:

    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);
          Console.WriteLine("Table {0} already exists", tableName);
      return table;
  • 以下代码演示了如何在表中插入数据:The following code shows how to insert data into the table:

    public static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
      if (entity == null)
          throw new ArgumentNullException("entity");
          // 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;
          if (result.RequestCharge.HasValue)
              Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
          return insertedCustomer;
      catch (StorageException e)
  • 以下代码演示了如何查询表中的数据:The following code shows how to query data from the table:

    public static async Task<CustomerEntity> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
          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);
          if (result.RequestCharge.HasValue)
              Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
          return customer;
      catch (StorageException e)
  • 以下代码演示了如何删除表中的数据:The following code shows how to delete data from the table:

    public static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
          if (deleteEntity == null)
              throw new ArgumentNullException("deleteEntity");
          TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
          TableResult result = await table.ExecuteAsync(deleteOperation);
          if (result.RequestCharge.HasValue)
              Console.WriteLine("Request Charge of Delete Operation: " + result.RequestCharge);
      catch (StorageException e)

更新连接字符串Update your connection string

现在返回到 Azure 门户,获取连接字符串信息,并将其复制到应用。Now go back to the Azure portal to get your connection string information and copy it into the app. 这样,应用程序就可以与托管的数据库进行通信。This enables your app to communicate with your hosted database.

  1. Azure 门户中,单击“连接字符串”。In the Azure portal, click Connection String. 使用窗口右侧的复制按钮复制“主连接字符串”。Use the copy button on the right side of the window to copy the PRIMARY CONNECTION STRING.


  2. 在 Visual Studio 中打开 Settings.json 文件。In Visual Studio, open the Settings.json file.

  3. 将门户中的“主连接字符串”粘贴到 StorageConnectionString 值中。Paste the PRIMARY CONNECTION STRING from the portal into the StorageConnectionString value. 粘贴引号内的字符串。Paste the string inside the quotes.

      "StorageConnectionString": "<Primary connection string from Azure portal>"
  4. 按 CTRL+S 保存 Settings.json 文件。Press CTRL+S to save the Settings.json file.

现已使用与 Azure Cosmos DB 进行通信所需的所有信息更新应用。You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

生成并部署应用Build and deploy the app

  1. 在 Visual Studio 中,右键单击“解决方案资源管理器”中的“CosmosTableSamples”项目,然后单击“管理 NuGet 包”。 In Visual Studio, right-click on the CosmosTableSamples project in Solution Explorer and then click Manage NuGet Packages.

    管理 NuGet 包

  2. 在 NuGet 的“浏览”框中,键入 Microsoft.Azure.Cosmos.Table。In the NuGet Browse box, type Microsoft.Azure.Cosmos.Table. 这样会查找 Cosmos DB 表 API 客户端库。This will find the Cosmos DB Table API client library. 请注意,此库目前仅适用于 .NET Framework 和 .NET Standard。Note that this library is currently available for .NET Framework and .NET Standard.

    NuGet 的“浏览”选项卡

  3. 单击“安装”以安装 Microsoft.Azure.Cosmos.Table 库。Click Install to install the Microsoft.Azure.Cosmos.Table library. 这会安装 Azure Cosmos DB 表 API 包和所有依赖项。This installs the Azure Cosmos DB Table API package and all dependencies.

  4. 运行整个应用时,示例数据将插入到表实体中,运行结束时会删除这些数据,因此,如果运行整个示例,你将看不到插入的任何数据。When you run the entire app, sample data is inserted into the table entity and deleted at the end so you won't see any data inserted if you run the whole sample. 但是,可以插入一些断点来查看数据。However you can insert some breakpoints to view the data. 打开 BasicSamples.cs 文件并右键单击第 52 行,选择“断点”,然后选择“插入断点”。 Open BasicSamples.cs file and right-click on line 52, select Breakpoint , then select Insert Breakpoint. 在第 55 行中插入另一个断点。Insert another breakpoint on line 55.


  5. 按 F5 运行应用程序。Press F5 to run the application. 控制台窗口会显示 Azure Cosmos DB 中新的表数据库的名称(在本例中为 demoa13b1)。The console window displays the name of the new table database (in this case, demoa13b1) in Azure Cosmos DB.


    点击第一个断点后,返回到 Azure 门户中的数据资源管理器。When you hit the first breakpoint, go back to Data Explorer in the Azure portal. 单击“刷新”按钮,展开 demo* 表,然后单击“实体”。Click the Refresh button, expand the demo* table, and click Entities. 右侧的“实体”选项卡将显示为 Walter Harp 添加的新实体。The Entities tab on the right shows the new entity that was added for Walter Harp. 请注意,新实体的电话号码为 425-555-0101。Note that the phone number for the new entity is 425-555-0101.


    如果收到说明在运行项目时无法找到 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:

       <None Update="Settings.json">
  6. 关闭数据资源管理器中的“实体”选项卡。Close the Entities tab in Data Explorer.

  7. 按 F5,运行应用到下一个断点。Press F5 to run the app to the next breakpoint.

    点击该断点后,切换回 Azure 门户,再次单击“实体”以打开“实体”选项卡,请注意该电话号码已更新为 425-555-0105。 When you hit the breakpoint, switch back to the Azure portal, click Entities again to open the Entities tab, and note that the phone number has been updated to 425-555-0105.

  8. 按 F5 运行该应用。Press F5 to run the app.

    该应用添加的实体可在表 API 目前不支持的高级示例应用中使用。The app adds entities for use in an advanced sample app that the Table API currently does not support. 该应用然后会删除示例应用创建的表。The app then deletes the table created by the sample app.

  9. 在控制台窗口中,按 Enter 结束应用的执行。In the console window, press Enter to end the execution of the app.

在 Azure 门户中查看 SLAReview SLAs in the Azure portal

Azure 门户监视 Cosmos DB 帐户吞吐量、存储、可用性、延迟和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服务级别协议 (SLA) 关联的指标的图表显示与实际性能相比的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此套指标使得监视 SLA 十分透明。This suite of metrics makes monitoring your SLAs transparent.

若要查看指标和 SLA,请执行以下操作:To review metrics and SLAs:

  1. 在 Cosmos DB 帐户的导航菜单中选择“指标” 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 选择一个选项卡,如“延迟” ,然后选择右侧的时间范围。Select a tab such as Latency, and select a timeframe on the right. 比较图表上的“实际” 和“SLA” 线。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 指标套件

  3. 查看其他选项卡上的指标。Review the metrics on the other tabs.

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要删除资源,请执行以下操作:To delete the resources:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。In the Azure portal Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.


  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.


  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

在本快速入门教程中,已了解如何创建 Azure Cosmos DB 帐户、使用数据资源管理器创建表和运行应用。In this quickstart, you've learned how to create an Azure Cosmos DB account, create a table using the Data Explorer, and run an app. 现在可以使用表 API 进行数据查询了。Now you can query your data using the Table API.