TableStorage お試し

はじめに

StorageClient ライブラリを使って Windows Azure Storage Service の Table を試してみます。Windows Azure のキーはまだ持って無いので、今回も Development Storage での話になりますが…。

下準備

public class CustomerEntity : TableStorageEntity
{
    public CustomerEntity(string partitionKey, string rowKey) : base(partitionKey, rowKey) {}
    public CustomerEntity() : base() {}

    public string Code { get;set; }
    public string Name { get;set; }
}

public class CustomerDataServiceContext : TableStorageDataServiceContext
{
    public CustomerDataServiceContext(StorageAccountInfo accountInfo) : base(accountInfo)
    {
    }

    public const string CustomerTableName = "CustomerTable";

    public IQueryable<CustomerEntity> CustomerTable
    {
        get
        {
            return this.CreateQuery<CustomerEntity>(CustomerTableName);
        }
    }
}

TableStorage を使ってみます

// 構成ファイルからアカウント情報を取得する
StorageAccountInfo account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();

// Table にアクセスするコンテキストを作成
CustomerDataServiceContext svc = new CustomerDataServiceContext(account);
svc.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));

// 'CustomerTable' を作成
TableStorage.CreateTablesFromModel(typeof(CustomerDataServiceContext), account);

// テーブルに CustomerEntity を1件追加
svc.AddObject(CustomerDataServiceContext.CustomerTableName,
    new CustomerEntity("customer", "entity") { Code = "0001", Name = "Microsoft" });
svc.SaveChangesWithRetries();

// TableStorage からデータを全て取得するクエリを作成
var qResult = from c in svc.CustomerTable
              select c;
TableStorageDataServiceQuery<CustomerEntity> q = new TableStorageDataServiceQuery<CustomerEntity>(qResult as DataServiceQuery<CustomerEntity>, svc.RetryPolicy);

// クエリを実行
IEnumerable<CustomerEntity> res = q.ExecuteAllWithRetries();

// 取得したデータを出力する
foreach (CustomerEntity c in res)
{
    Console.WriteLine("Code:{0}, Name:{1}", c.Code, c.Name);
}

Development Storage では、動的に Table を作成することが出来ません。Table は事前に用意しておく必要があります。
このコードの実行結果は次の通りです。

Code:0001, Name:Microsoft

テーブルからデータを削除

var qResult = from c in svc.CreateQuery<CustomerEntity>(tableName)
              select c;

TableStorageDataServiceQuery<CustomerEntity> q = new TableStorageDataServiceQuery<CustomerEntity>(qResult as DataServiceQuery<CustomerEntity>);
IEnumerable<CustomerEntity> res = q.ExecuteAllWithRetries();

foreach (CustomerEntity s in res)
{
    svc.DeleteObject(s);
    svc.SaveChangesWithRetries();
}

まとめ

LINQ to SQL みたいな記述で、Table に対するデータの追加・削除・取得が出来ました。LINQ を使えるというのが、Queue や Blob とは異なりますね。

Windows Azure Storage Service の Table はリレーショナルデータベースではありませんが、LINQ に慣れていれば Queue や Blob よりも違和感は少ないと思います。