Q80: How do I retrieve a single entity from Table Storage using TableOperation?

In this question, we will see how to retrieve the data from the Table storage. The below example code demonstrates how to construct a simple query to retrieve a single, specific entity. The following code uses a TableOperation to specify an item with PartitionKey 'RawMaterial' and RowKey 'R001'. This method returns just one entity, rather than a collection, and the returned value in TableResult.Result is an ItemEntity. Specifying both PartitionKey and RowKey in a query, is the fastest way to retrieve a single entity from the Table.

// Retrieve the storage account from the connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

CloudTableClient client = account.CreateCloudTableClient();
CloudTable table = client.GetTableReference("items");

TableOperation retrieveOperation= TableOperation.Retrieve<ItemEntity>("RawMaterial","R001");

TableResult query = table.Execute(retrieveOperation);
if (query.Result != null)
	Console.WriteLine("Item: {0}", ((ItemEntity)query.Result).Name);

When we execute this code, the entity is retrieved and the Item name is displayed. There are many ways of querying the data in the table and we will discuss about them in the coming questions. In the earlier versions of the .Net Storage library 2.x, LINQ was used to query tables. Storage Client library 2.0 utilizes the new Microsoft.Data.OData library, and this offers greater performance. However, LINQ can still be used to query table storage and the classes are in Microsoft.WindowsAzure.Storage.Table.DataServices library.

In Storage Client library 2.0, a lightweight query class 'TableQuery' is included. Using this class we can construct complex queries, but the syntax is not as simple as in LINQ.