Cloud table CRUD operation in azure storage table

Let’s learn all CRUD operation in azure cloud table.

In earlier post, we have learned how to create cloud table and insert data, so, now we learn how to retrieve and update data, finally delete them.

I continue with earlier example of customer table, we retrieve data from customer table based on row key and partition key, then we change customer details and save them.

Customer _cust=  LoadCustomerData(_rowKey, _partitionKey)

When we create any Entity inherited from Microsoft.Azure.Cosmos.Table class, two base property (RowKey and PartitionKey) we get by deafult, which helps finding unique row from any table.

Note: In this CRUD example, we have used the reference of cosmos table api, Microsoft.Azure.Cosmos.Table namespace, if you are using reference of Microsoft.WindowsAzure.Storage.Table namespace, all syntax will remain same, part from few minor changes, look at the complex object azure table example

public class Customer : TableEntity
{
    public Customer()
    { 

    }
                
    //new string  RowKey { get; set; }
    //new string PartitionKey { get; set; }

    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Mobile { get; set; }
    public string Email { get; set; }
        
}

Just think of loading the above customer entity based on row key and partition key we are getting from query string ( or any other sources).

public void OnGet()
{    
    var _rowKey = Request.Query["rkey"];
    var _partitionKey = Request.Query["pkey"];
    Customer _cust=  LoadCustomerData(_rowKey, _partitionKey).Result;

    if (_cust != null)
    {
        // loading all properties 

        RowKeyThis = _cust.RowKey;
        PartitionKeyThis = _cust.PartitionKey;
        CustomerFirstName = _cust.Firstname;
        CustomerLastName = _cust.Lastname;
        Mobile = _cust.Mobile;
        Email = _cust.Email;
    }
}

As you can see in above code, i have called LoadCustomerData(_rowKey, _partitionKey) method with two parameters value to get all details about a customer.

Retrieve customer details from cloud table

In following code, we see two different ways of retrieving data for a particular customer based on parameter value.

One, fetching call customers in ExecuteQuery method, and then picking the one matching with parameter value, using simple linq query, this will work perfectly, but then if you have large number of customers, then fetching all the data from database may not be good idea, actually bad! Still let’s learn the way!

TableQuery<Customer> _query = new TableQuery<Customer>();

IEnumerable<Customer> _result= customerTable.ExecuteQuery(_query);

Customer _cust = _result.ToList()
.Where(c => c.PartitionKey == partitionkey &&
c.RowKey == rowKey)
.FirstOrDefault<Customer>();

Though above code is working fine, but we are not implementing, we learn Retrieve operation TableOperation.Retrieve<Customer>(partitionkey, rowKey), this will only fetch the row from database if both parameters value match.

Task<Customer> LoadCustomerData(string rowKey, string partitionkey)
{

Customer customerData = new Customer();
string _message = "Load customer data"; 
           
string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
var storageAccount = CloudStorageAccount.Parse(_storageConnection);
	  
var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
var customerTable = tableClient.GetTableReference("custTable");                
Customer _cust = null;
		
// retrive Customer using partitionkey and rowkey
TableOperation _retriveOperation = TableOperation.Retrieve<Customer>(partitionkey, rowKey);

TableResult _tableResult=  customerTable.ExecuteAsync(_retriveOperation).Result;
		
// converting TableResult to object 
if(_tableResult!=null)
	_cust = _tableResult.Result as Customer;

customerData = _cust;  
           
   return Task.FromResult(customerData);	
 }

Now, in your razor page, you can access each property value, it would be nice, if you create a form and populate those values, where we can make changes and update the customer details, we learn update function, Replace and Merge.

Update cloud table in azure storage

I am not adding all the properties here in razor page code, will focus on only few values that helps understanding the cloud table update operation.

<form method="post">
<input type="hidden" asp-for="RowKeyThis" />
<input type="hidden" asp-for="PartitionKeyThis" />
<div class="form-group">First Name: <div><input type="text" asp-for="CustomerFirstName" /></div></div>
			
<div style="padding:15px;text-align:center;">   
    <button asp-page-handler="UpdateCustomer" class="btn-success">Update Customer</button>    
</div>
</form>

We are calling "UpdateCustomer" method from above code, so we have to write OnPost + UpdateCustomer in code behind file.

After setting all customer data, creating a table operation InsertOrMerge TableOperation.InsertOrMerge(_customer);, which means if there is no record, it will insert one, else it will merge with exisiting record.

public async Task<IActionResult> OnPostUpdateCustomer()
{
    string _message = "update customer";
    string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
    var storageAccount = CloudStorageAccount.Parse(_storageConnection);
    var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
            
    var customerTable = tableClient.GetTableReference("custTable");
    Customer _customer = new Customer()
    {
        RowKey = RowKeyThis,
        PartitionKey = PartitionKeyThis,
        Firstname = CustomerFirstName         
    };
                               
    var queryReplace = TableOperation.InsertOrMerge(_customer);
              
    TableResult _result =   await customerTable.ExecuteAsync(queryReplace);             
                        
    return Redirect("azTabCustomer");
}

We could also use another similar operation, InsertOrReplace TableOperation.InsertOrReplace(_customer);, which does almost same job, replace or insert.

You can use the retrieve function to check if data is updated correctly or not.

Delete data from Cloud Table

To delete one customer data we use the same above form, with just a different button called delete.

<button asp-page-handler="DeleteCustomer" class="btn-danger">Delete Customer</button>

Just call the DeleteCustomer method on post, you could use a hyperlink also, either set all fields value or set ETag = "*" with rk and pk

public async Task<IActionResult> OnPostDeleteCustomer()
{
string _message = "delete customer";
string _storageConnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
var storageAccount = CloudStorageAccount.Parse(_storageConnection);
var tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
var customerTable = tableClient.GetTableReference("custTable");
	
Customer _customer = new Customer()
{
    RowKey = RowKeyThis,
    PartitionKey = PartitionKeyThis,
    ETag = "*"
};

var queryReplace = TableOperation.Delete(_customer);

await customerTable.ExecuteAsync(queryReplace);

return Redirect("azTabCustomer");
}

Hope you could implement all azure cloud table crud operations successfully.

 
Azure Cloud Tutorial
learn azure cloud development

Let's learn how to use Azure Cloud Storage system from Ap.net core c# application.

Data Analysis
learn Artificial Intelligence
Add Data to Azure Cloud Table
Learn Azure Cloud Development