Retrieving Records - Understanding Table Storage - Part Three

In this article, we will see how to retrieve records from an Azure Table Storage. Before working with this demo, I have already added two more records to our table in the same partition called Customer1 and Customer2,

Step 1

First, we are going to see how to retrieve a single record from the table. Open your project, remove or comment the method call and method for creating the customer that we did in the previous exercise and add the following method RetriveCustomer, with parameters, CloudTable, PartitionKey and the RowKey to uniquely identify the customer to your class.

  1. public static void RetrieveCustomer(CloudTable table, string partitionKey, string rowKey)  
  2. {  
  3.    TableOperation tableOperation = TableOperation.Retrieve<Customer>(partitionKey, rowKey);  
  4.    TableResult tableResult = table.Execute(tableOperation);  
  5.    Console.WriteLine(((Customer)tableResult.Result).CustomerName);  
  6. }  

 Add the method call code to your Main method after the code for getting table reference.

  1. RetrieveCustomer(table, "registered""[email protected]");  
  2. Console.ReadKey();  

Azure 

Step 2

To get the result, we have to create a constructor for the class Customer without parameters. Open Customer.cs class in the Entities folder and copy the following code to the class.

  1. public Customer()  
  2. {  
  3.   
  4. }  

Azure 

Step 3

Run your application and you can see the corresponding name is retrieved according to the Partition-key and Row-key we provided.
 
Azure 

Step 4

Now we will see how to retrieve all the records in the table within a particular partition. Remove or comment the method call and method to retrieve single customer and add the following method to your class which will retrieve all the records. Here we need to pass just the table reference as a parameter and use a filter condition to get the records from the particular partition.

  1. static void RetrieveAllCustomers(CloudTable table)  
  2. {  
  3.    TableQuery<Customer> query = new TableQuery<Customer>()  
  4.    .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "registered"));  
  5.    foreach (Customer customer in table.ExecuteQuery(query))  
  6.    {  
  7.       Console.WriteLine(customer.CustomerName + " " + customer.CustomerEmail);  
  8.    }  
  9. }  

Copy the following code to your Main method to call the method we just added.

  1. RetrieveAllCustomers(table);  

Azure 

Step 5

Run your application and you can see that all the records in the particular partition have been listed.
 
Azure