Deleting Records - Understanding Table Storage - Part Six

Performing a delete operation on an entity in a table is pretty much the same process using the TableOperation class. Instead of using the Replace method, we just use the Delete method. TableOperation.Delete creates the table delete operation object that has to be executed against the table. Record to be deleted is identified by Row-key and Partition-key and will only be created if the record exists. Otherwise it will throw the application.

Step 1

Open the previous project, remove the method for Batch operations and its method call and copy paste the following code to the class. Here, the first method is the same method that we used in Update exercise, that is the method to return a single record and in the second method, we use delete instead of update.

  1. public static Customer RetrieveCustomer(CloudTable table, string partitionKey, string rowKey)  
  2. {  
  3.    TableOperation tableOperation = TableOperation.Retrieve<Customer>(partitionKey, rowKey);  
  4.    TableResult tableResult = table.Execute(tableOperation);  
  5.    return tableResult.Result as Customer;  
  6. }  
  8. static void DeleteCustomer(CloudTable table, Customer customer)  
  9. {  
  10.    TableOperation delete = TableOperation.Delete(customer);  
  11.    table.Execute(delete);  
  12.    Console.WriteLine("Record deleted");  
  13. }  

Step 2

Add the following code to your Main method after the code for getting table reference before the RetriveAllCustomers Method. Here it will get the return value from the RetrieveCustomer method and then we will delete the corresponding method.

  1. Customer customerEntity = RetrieveCustomer(table, "registered""");  
  2. DeleteCustomer(table, customerEntity);  
Step 3

Run your application and you can see the Record deleted message and the corresponding value is missing from the result of GetAllCustomers method.

Step 4

If you want to drop a table completely you can use the DeleteIfExists method which will drop the table in Table storage if it exists.

Remove all the methods and method calls from your program and copy the following method to your class.

  1. public static void DropTable(CloudTable table)  
  2. {  
  3.    var status = table.DeleteIfExists();  
  4.    if (status == true) Console.WriteLine("Table deleted");  
  5.    else Console.WriteLine("Table does not exists");  
  6. }  

Call the method by pasting the following code in the Main method

  1. DropTable(table);  

Step 5

Run your application and you can see the Table deleted message and you can verify with the portal also.