You are currently viewing Use .NET Client SDK with Azure Table Storage

Use .NET Client SDK with Azure Table Storage

Azure table storage can be used for storing the NoSQL structured data. There is premium offering, CosmosDB, which is recommended by Azure. But there may be few differences because of which you may want to go ahead with table storage.

This article is good starting point if you are new to Azure table storage. This article demonstrates basic topics like creating azure table storage and how to use .NET client SDK in your application.

Create storage account

For creating a new table in table storage, you will have to create a storage account first. We have created storage account in previous article of AZ-203 series.

Create the table

Once storage account is created, you can create table in table storage using Portal, Azure CLI or using storage explorer.

Let’s use Azure portal to create the new table.

Login to Azure Portal and Navigate to the storage account we created. Once you click on the resource, you will be shown with overview blade, where you can see different buttons for blob, table, files, queue creation.

Click on the Tables option.

Once you click on tables, you will be navigated to a page where list of all tables is shown. As this is newly created storage account, you will not be able to see any tables in that list.

But you can click on “+ Table” button at the top and it will bring up a popup where you can enter the table name. After entering appropriate table name, click on Ok. This will create a new table in table storage.

Alternatively if you have storage explorer installed, you can navigate to the storage account and expand the node to see tables node. If you right click on the tables node, you will be shown an option to add new table.

We have created the table in Azure Table Storage. Before we go ahead and work with this table, let’s try to understand few concepts.

Understanding Couple of Concepts

Before starting on writing the code, let’s have a look at some basic terminology.

Entity

It is very natural to assume that table storage will be a collection of tables and each table will have some rows in them.

From terminology perspective, first half of this assumption is correct and indeed, every table storage may contain one or more than one tables.

But, the tables does not contain rows. Table storage stores the NoSQL data and every “row” in this NoSQL data is called as entity.

Partition Key

The table storage organizes the data into different physical partitions. The partition key is the attribute of entity which is used to find appropriate partition for a record.

While selecting partition key, we should ensure that the data will be evenly distributed in different partitions. This even distribution will also help in better application performance.

For ex. If you are storing addresses of people in a country, you may want to have state name or ZIP code as partition key as it may result in almost even distribution of records. You may not want to choose the country name as partition key as this will lead all record to get stored in one partition.

Row Key

The concept of row key is simple. It is the “primary key” of the entities within same partition.

Performance Impact

Selecting appropriate partition key and row key is very very critical for optimal performance of your application.

You might have guessed that the fastest way to get any record from table storage is to query the data using both partition key and row key.

The second fastest way may be just to use row key and try to find out a record. In this case, the table storage service will check all partitions for that record.

And the least performant way may be not to use partition key and row key but use some other attribute of entity (e.g. user’s first name). In this search, the data will not be indexed and hence the search time would not be optimum.

Programming with . NET SDK

You need to add a NuGet package WindowsAzure.Storage in the application. You can either use Visual studio UI to add NuGet package reference, OR you can use below command on package manager terminal to add it.

Install-Package WindowsAzure.Storage

The below code gets reference to the storage account using the storage account connection string.

Once the account reference is there, it creates cloud table client and tries to get reference to the table with name “myfirsttable”.

If the table does not exists, then the CreateIfNotExistsAsync method creates the table in table storage.

string storageConnectionString = "DefaultEndpointsProtocol=https;"
    + "AccountName=[Storage Account Name]"
    + ";AccountKey=[Storage Account Key]"
    + ";EndpointSuffix=core.windows.net";

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable cloudTable = tableClient.GetTableReference("myfirsttable");
await cloudTable.CreateIfNotExistsAsync();

We will use below table entity for the demonstrating the CRUD operations. Please note that the customer entity is derived from table entity class and the constructor specifies the partition key and row key.

As this is just demonstration on how to use .NET SDK, it is fine to use first name and last name as row key and partition key. In real world, you may want to choose different keys based on domain of your application and kind of queries you will be wanting to execute on the data.

using Microsoft.WindowsAzure.Storage.Table;

public class CustomerEntity : TableEntity
{
    public CustomerEntity()
    {
    }

    public CustomerEntity(string lastName, string firstName)
    {
        PartitionKey = lastName;
        RowKey = firstName;
    }

    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

Below code can be used to insert new record or replace an existing one.

// Create entity instance
var entity = new CustomerEntity("Doe", "John");

// Create the InsertOrReplace table operation
var insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

// Execute the operation.
var result1 = await cloudTable.ExecuteAsync(insertOrMergeOperation);

To retrieve the record added in previous step:

Please note that partition key and row key are the values which are passed to this method for searching the record.

TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(partitionKey, rowKey);

TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomerEntity customer = result.Result as CustomerEntity;

To delete existing entity from the table storage:

TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
TableResult result = await table.ExecuteAsync(deleteOperation);

I hope this is provides a good information to get you started with Azure table storage programming. Let me know your thoughts.

Leave a Reply Cancel reply