Azure table storage - Simplest possible example

蹲街弑〆低调 提交于 2019-12-03 06:03:41

The simplest sample I could think of is this. You need to 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() { }
}

The answer to the seconds question, why are there two namespaces that provided more or less the same APIs, Azure Storage Client Library 2.0 contains a new simplified API. See link below.

What's New in Storage Client Library for .NET (version 2.0)

Thanks so much for this! Been searching for ages for a simple example of connecting to Azure Table Storage in your development environment. From your examples above I formulated the code below:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;

namespace Bootstrapping
{
  public class Builder
  {

    public void Run()
    {
      CloudStorageAccount storageAccount =
        CloudStorageAccount.Parse("UseDevelopmentStorage=true");
      CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

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

    }

  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!