Three things you should know about querying the Azure Table Storage SDK

1. .AsTableServiceQuery()

If your query spans multiple partitions, or exceeds the maximum number of entities allowed in a single request, you’ll get a subset of the results, and a continuation token to retrieve the remaining records. Adding AsTableServiceQuery() to the end of your statement will handle the continuation token for you.

var account = CloudStorageAccount.DevelopmentStorageAccount;
var context = new TableServiceContext(account.TableEndpoint.ToString(), account.Credentials);
var query = context.CreateQuery<Foo>("Foo").AsTableServiceQuery();

It will also introduce a retry policy for you, in case your request failed.

2. .ToString()

Calling ToString() on a table service query will give you URL that will be used to access the Table Storage API. This is very useful for debugging your queries.

So this:

var account = CloudStorageAccount.DevelopmentStorageAccount;
var context = new TableServiceContext(account.TableEndpoint.ToString(), account.Credentials);
var query = context.CreateQuery<Foo>("Foo").Where(x => x.PartitionKey == "123");
Console.WriteLine(query);

Produces this:

http://127.0.0.1:10002/devstoreaccount1/Foo()?$filter=PartitionKey eq '123'

In fact Entity Framework queries do a similar thing (with some worrying SQL), as do Expressions.

3. It’s plain old reflection

The Table Storage SDK will simply map the properties in the Table, onto the type you have supplied. This means you could read and write the same entities using different classes. This could be useful if you want to model inheritance, or extend the properties you store for certain parts of your code. The only drawback is that you need a new context object when you want to switch which type maps to table.

Consider two classes, Bar inherits from Foo.

public class Foo : TableServiceEntity
{
    public string FooVariable { get; set; }        
}

public class Bar : Foo
{
    public string BarVariable { get; set; }
}

This code will write a Bar, and then read the entity back as a Foo:

var account = CloudStorageAccount.DevelopmentStorageAccount;
var context = new TableServiceContext(account.TableEndpoint.ToString(), account.Credentials);
context.AddObject("Foo", new Bar { PartitionKey = "1", RowKey= "2", FooVariable = "FOO", BarVariable = "BAR" });
context.SaveChanges();

context = new TableServiceContext(account.TableEndpoint.ToString(), account.Credentials);
var foo = context.CreateQuery<Foo>("Foo").AsTableServiceQuery().FirstOrDefault();
About these ads