您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

如何开始使用 Azure 表存储和 Visual Studio 连接服务How to get started with Azure Table storage and Visual Studio connected services

本文内容

提示

试用 Microsoft Azure 存储资源管理器

Microsoft Azure 存储资源管理器是 Microsoft 免费提供的独立应用,适用于在 Windows、macOS 和 Linux 上以可视方式处理 Azure 存储数据。

本文介绍通过使用 Visual Studio 中的“连接服务”功能在 ASP.NET Core 项目中创建或引用 Azure 存储帐户之后,如何开始在 Visual Studio 中使用 Azure 表存储。执行“连接服务”操作会安装相应的 NuGet 程序包,以访问项目中的 Azure 存储,并将存储帐户的连接字符串添加到项目配置文件中。(有关 Azure 存储的常规信息,请参阅存储文档。)

Azure 表存储服务使用户可以存储大量结构化数据。该服务是一个 NoSQL 数据存储,接受来自 Azure 云内部和外部的通过验证的呼叫。Azure 表最适合存储结构化非关系型数据。有关使用 Azure 表存储的更多常规信息,请参阅 Get started with Azure Table storage using .NET(通过 .NET 开始使用 Azure 表存储)。

若要开始,首先在你的存储帐户中创建一个表。然后本文将演示如何运用 C# 创建表,以及如何执行基本的表操作,如添加、修改、读取和删除表项。代码使用适用于 .NET 的 Azure 存储客户端库。有关 ASP.NET 的详细信息,请参阅 ASP.NET

某些 Azure 存储 API 为异步,而本文中的代码假定正在使用异步方法。有关详细信息,请参阅异步编程

使用代码访问表Access tables in code

要访问 ASP.NET Core 项目中的表,需要将下列事项包含在任何访问 Azure 表存储的 C# 源文件中。

  • 添加必要的 using 语句:
  1. using Microsoft.WindowsAzure.Storage;
  2. using Microsoft.WindowsAzure.Storage.Table;
  3. using System.Threading.Tasks;
  • 获取表示存储帐户信息的 CloudStorageAccount 对象。通过存储帐户的名称和帐户密钥,使用以下代码(位于 appSettings.json 的存储连接字符串中):
  1. CloudStorageAccount storageAccount = new CloudStorageAccount(
  2. new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
  3. "<name>", "<account-key>"), true);
  • 获取 CloudTableClient 对象,以引用存储帐户中的表对象:
  1. // Create the table client.
  2. CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
  • 获取 CloudTable 引用对象,以引用特定的表和实体:
  1. // Get a reference to a table named "peopleTable"
  2. CloudTable peopleTable = tableClient.GetTableReference("peopleTable");

使用代码创建表Create a table in code

若要创建 Azure 表,请创建异步方法并在其中调用 CreateIfNotExistsAsync()

  1. async void CreatePeopleTableAsync()
  2. {
  3. // Create the CloudTable if it does not exist
  4. await peopleTable.CreateIfNotExistsAsync();
  5. }

将实体添加到表Add an entity to a table

要将实体添加到表,请创建用于定义实体的属性的类。以下代码将定义一个名为 CustomerEntity 的实体类,其使用客户的名字和姓氏分别作为行键和分区键。

  1. public class CustomerEntity : TableEntity
  2. {
  3. public CustomerEntity(string lastName, string firstName)
  4. {
  5. this.PartitionKey = lastName;
  6. this.RowKey = firstName;
  7. }
  8. public CustomerEntity() { }
  9. public string Email { get; set; }
  10. public string PhoneNumber { get; set; }
  11. }

涉及这些实体的表操作将使用之前在代码访问表中创建的 CloudTable 对象。TableOperation 对象表示将完成的操作。以下代码示例演示如何创建 CloudTable 对象和 CustomerEntity 对象。为准备此操作,会创建一个 TableOperation 以将客户实体插入该表中。最后,通过调用 CloudTable.ExecuteAsync 执行此操作。

  1. // Create a new customer entity.
  2. CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
  3. customer1.Email = "Walter@contoso.com";
  4. customer1.PhoneNumber = "425-555-0101";
  5. // Create the TableOperation that inserts the customer entity.
  6. TableOperation insertOperation = TableOperation.Insert(customer1);
  7. // Execute the insert operation.
  8. await peopleTable.ExecuteAsync(insertOperation);

插入一批实体Insert a batch of entities

可以通过单个写入操作将多个实体插入表中。以下代码示例将创建两个实体对象(“Jeff Smith”和“Ben Smith”),使用 Insert 方法将它们添加到 TableBatchOperation 对象,并通过调用 CloudTable.ExecuteBatchAsync 来启动操作。

  1. // Create the batch operation.
  2. TableBatchOperation batchOperation = new TableBatchOperation();
  3. // Create a customer entity and add it to the table.
  4. CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff");
  5. customer1.Email = "Jeff@contoso.com";
  6. customer1.PhoneNumber = "425-555-0104";
  7. // Create another customer entity and add it to the table.
  8. CustomerEntity customer2 = new CustomerEntity("Smith", "Ben");
  9. customer2.Email = "Ben@contoso.com";
  10. customer2.PhoneNumber = "425-555-0102";
  11. // Add both customer entities to the batch insert operation.
  12. batchOperation.Insert(customer1);
  13. batchOperation.Insert(customer2);
  14. // Execute the batch operation.
  15. await peopleTable.ExecuteBatchAsync(batchOperation);

获取分区中的所有实体Get all of the entities in a partition

若要查询表以获取某个分区中的所有实体,请使用 TableQuery 对象。以下代码示例指定了一个筛选器,以筛选分区键为“Smith”的实体。此示例会将查询结果中每个实体的字段输出到控制台。

  1. // Construct the query operation for all customer entities where PartitionKey="Smith".
  2. TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"));
  3. // Print the fields for each customer.
  4. TableContinuationToken token = null;
  5. do
  6. {
  7. TableQuerySegment<CustomerEntity> resultSegment = await peopleTable.ExecuteQuerySegmentedAsync(query, token);
  8. token = resultSegment.ContinuationToken;
  9. foreach (CustomerEntity entity in resultSegment.Results)
  10. {
  11. Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
  12. entity.Email, entity.PhoneNumber);
  13. }
  14. } while (token != null);

获取单个实体Get a single entity

可以编写查询以获取单个特定实体。以下代码使用 TableOperation 对象来指定名为“Ben Smith”的客户。此方法只返回一个实体,而不是一个集合,并且 TableResult.Result 中返回的值为 CustomerEntity 对象。在查询中指定分区键和行键是从 Table 服务中检索单个实体最快的方法。

  1. // Create a retrieve operation that takes a customer entity.
  2. TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");
  3. // Execute the retrieve operation.
  4. TableResult retrievedResult = await peopleTable.ExecuteAsync(retrieveOperation);
  5. // Print the phone number of the result.
  6. if (retrievedResult.Result != null)
  7. Console.WriteLine(((CustomerEntity)retrievedResult.Result).PhoneNumber);
  8. else
  9. Console.WriteLine("The phone number could not be retrieved.");

删除实体Delete an entity

可以在找到实体后将其删除。以下代码查找并删除名为“Ben Smith”的客户实体:

  1. // Create a retrieve operation that expects a customer entity.
  2. TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>("Smith", "Ben");
  3. // Execute the operation.
  4. TableResult retrievedResult = await peopleTable.ExecuteAsync(retrieveOperation);
  5. // Assign the result to a CustomerEntity object.
  6. CustomerEntity deleteEntity = (CustomerEntity)retrievedResult.Result;
  7. // Create the Delete TableOperation and then execute it.
  8. if (deleteEntity != null)
  9. {
  10. TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
  11. // Execute the operation.
  12. await peopleTable.ExecuteAsync(deleteOperation);
  13. Console.WriteLine("Entity deleted.");
  14. }
  15. else
  16. Console.WriteLine("Couldn't delete the entity.");

后续步骤Next steps

现在,已了解有关 Azure 表存储的基础知识,可单击下面的链接来了解更复杂的存储任务。