Azure表存储 - 最简单的示例

Rub*_*bio 16 azure-table-storage

每当学习新技术时,我都想写出最简单的例子.通常这意味着具有最少引用数量的控制台应用程序.我一直在尝试编写一个读取和写入Azure表存储的应用程序,但收效甚微.我已经使用这个操作指南作为基础,但尝试在Main方法中做所有事情.类似的方法适用于blob存储,但是表存储很麻烦.

我能够使用此代码创建一个表.

static void Main(string[] args)
{
    Microsoft.WindowsAzure.Storage.Table.CloudTableClient tableClient =
    new Microsoft.WindowsAzure.Storage.Table.CloudTableClient(
        new Uri("http://mystorage.table.core.windows.net/"),
    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("[somename]", "[somekey]"));

    CloudTable table = tableClient.GetTableReference("people");
    table.CreateIfNotExists();
}
Run Code Online (Sandbox Code Playgroud)

运行此代码后,我可以使用Azure存储资源管理器在我的存储中看到一个表.(还没弄明白如何在manage.windowsazure.com上查看该表.)

但是,如果我尝试插入记录(如前面提到的操作指南中所述),我会收到冲突409 EntityAlreadyExists.Azure Storage Explorer不会在我的表中显示任何记录.

CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
customer1.Email = "Walter@contoso.com";
customer1.PhoneNumber = "425-555-0101";

TableOperation insertOperation = TableOperation.Insert(customer1);
table.Execute(insertOperation);
Run Code Online (Sandbox Code Playgroud)

此外,我对两个重叠的命名空间感到困惑.Microsoft.WindowsAzure.Storage.Table和Microsoft.WindowsAzure.StorageClient都包含例如CloudTableClient类.为什么有两个客户端命名空间,我应该使用哪个?

编辑结果记录确实存在.只需双击Azure表格资源管理器中的表格,就不会显示表格内容.您必须单击"查询".最后一个问题仍然存在.为什么这两个命名空间?

Rub*_*bio 19

我能想到的最简单的样本就是这个.您需要NuGet WindowsAzure.Storage 2.0.

static void Main(string[] args)
{
  try
  {
     CloudStorageAccount storageAccount =
        CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=<your_storage_name>;AccountKey=<your_account_key>");
     CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

     CloudTable table = tableClient.GetTableReference("people");
     table.CreateIfNotExists();

     CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
     customer1.Email = "Walter@contoso.com";
     customer1.PhoneNumber = "425-555-0101";

     // Create the TableOperation that inserts the customer entity.
     var insertOperation = TableOperation.Insert(customer1);

     // Execute the insert operation.
     table.Execute(insertOperation);

     // Read storage
     TableQuery<CustomerEntity> query =
        new TableQuery<CustomerEntity>()
           .Where(TableQuery.GenerateFilterCondition("PartitionKey",
               QueryComparisons.Equal, "Harp"));
     var list = table.ExecuteQuery(query).ToList();
   }
   catch (StorageException ex)
   {
       // Exception handling here.
   }
}

public class CustomerEntity : TableEntity
{
    public string Email { get; set; }
    public string PhoneNumber { get; set; }

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

    public CustomerEntity() { }
}
Run Code Online (Sandbox Code Playgroud)

对于秒问题的答案,为什么有两个命名空间提供了或多或少相同的API,Azure Storage Client Library 2.0包含一个新的简化API.见下面的链接.

Storage Client Library for .NET(2.0版)的新增功能