Azure Table Storage – QueryAsync

Quick one today. I have been playing around with Azure Table Storage using the “WindowsAzure.Storage” library in dotnet, and was failing to find anything useful on querying multiple rows. Using the ‘TableContinuationToken’ was a little confusing to me, and a lot of the example on the net are out of date (who knows, this may also be out of date by the time you read it!).

The below extension method works for at least WindowsAzure.Storage v9.3.3.

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;

/// <summary>
/// Get rows from an Azure Storage Table.
/// </summary>
/// <typeparam name="TEntity">type of entity, extending Microsoft.WindowsAzure.Storage.Table.TableEntity</typeparam>
/// <param name="table">the CloudTable, e.g. _tableClient.GetTableReference("table_name");</param>
/// <param name="tableQuery">a TableQuery object, e.g. for filter, select</param>
/// <returns></returns>
public static async Task<List<TEntity>> QueryAsync<TEntity>(
	this CloudTable table,
	TableQuery<TEntity> tableQuery) where TEntity : TableEntity, new()
	List<TEntity> results = new List<TEntity>();
	TableContinuationToken continuationToken = default;
		var queryResults = await table.ExecuteQuerySegmentedAsync(tableQuery, continuationToken);
		continuationToken = queryResults.ContinuationToken;
	} while (continuationToken != null);

	return results;

And here is how to use it:

public class MyEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
    public string AnotherField { get; set; }

var storageAccount = CloudStorageAccount.Parse(connectionString);
var tableClient  = storageAccount.CreateCloudTableClient();</p>
var table = tableClient.GetTableReference("table_name");

//To get all rows in a single partition
var tableQuery = new TableQuery<MyEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "partitionKey"));
List<MyEntity> results = await table.GetAsync<MyEntity>(tableQuery);

//To get all rows
var tableQuery = new TableQuery<MyEntity>();
List<MyEntity> results = await table.GetAsync<MyEntity>(tableQuery);

You can build up more complex queries using the TableQuery object, there is plenty of material that covers that, e.g. <;

That’s all folks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: