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

本快速入门介绍如何使用 .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.

先决条件Prerequisites

如果尚未安装 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 subscription, create a trial account before you begin.

创建数据库帐户Create a database 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 DescriptionDescription
    订阅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

    然后输入在 ID 中提供的同一唯一名称Then enter the same unique name as provided in ID
    选择“新建”。Select Create new. 然后输入帐户的新资源组名称。Then enter a new resource group name for your account. 为简单起见,可以使用与 ID 相同的名称。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.

    该 ID 只能使用小写字母、数字和连字符 (-) 字符。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 门户“通知”窗格

添加表Add a table

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

  1. 依次单击“数据资源管理器” > “新建表”。Click 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. / \ # ? 或尾随空格。Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    存储容量Storage capacity 固定 (10 GB)Fixed (10 GB) 使用默认值“固定 (10 GB)”。Use the default value of Fixed (10 GB). 此值是数据库的存储容量。This value is the storage capacity of the database.
    吞吐量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.

    单击 “确定”Click OK.

    数据资源管理器将显示新的数据库和表。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, click Entities, and then click Add Entity.

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

  2. 现在请将数据添加到 PartitionKey 值框和 RowKey 值框,并单击“添加实体”。Now add data to the PartitionKey value box and RowKey value box, and click 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
    

在 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.

更新连接字符串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:

     <ItemGroup>
       <None Update="Settings.json">
         <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
       </None>
     </ItemGroup>
    
  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

不再需要 Web 应用和 Azure Cosmos DB 帐户以后,即可删除创建的 Azure 资源,避免产生更多费用。When you're done with your web 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, select Resource groups on the far left. 如果左侧菜单处于折叠状态,请选择 “展开”按钮 将其展开。If the left menu is collapsed, select Expand button to expand it.

  2. 选择为本快速入门创建的资源组。Select the resource group you created for this quickstart.

    Azure 门户中的指标

  3. 在新窗口中选择“删除资源组”。In the new window, select Delete resource group.

    Azure 门户中的指标

  4. 在下一窗口中键入要删除的资源组的名称,然后选择“删除”。In the next window, type 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.