Joydip Kanjilal
Contributor

How to use Azure Table storage in .Net

how-to
Jan 14, 20196 mins
C#Cloud ComputingMicrosoft .NET

Take advantage of Azure Table storage in your .Net applications to store large amounts of key-value data in the Microsoft cloud

cloud computing - binary - data center - network server - storage
Credit: Thinkstock

Microsoft’s Azure cloud computing platform provides interoperable cloud computing services that are comprised of both open source and standards-based technologies. You can use an Azure storage account to work with all kinds of data including files, blobs, queues, and tables.

Azure Table storage is a scalable, non-relational, key-value storage system that you can leverage to store large volumes of data in the cloud. This article presents a discussion of Azure Table storage and how we can work with it in .Net.

Create a console application project in Visual Studio 2017

First off, let’s create a console application project in Visual Studio. If Visual Studio 2017 is up and running in your system, follow the steps outlined below to create the project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “Console App (.Net Framework)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Specify the location for the project.
  6. Select the Framework version you would like to use.
  7. Click OK to save the project.

Following these steps will result in a new console application project in Visual Studio. You can use this project to write and execute the programs given in the sections that follow.

Create a new Azure storage account

To work with blobs, files, tables, or queues in Azure, you will need an Azure storage account. An Azure storage account is a unique namespace in the Azure cloud that can be used for storage and retrieval of data. Naturally, you will first need to create an Azure account (if you don’t have one) and then use it to create an Azure storage account. If you don’t have an Azure account, you can create a free Azure account here.

Once you have an Azure account, you can follow the steps given below to create a storage account in Azure:

  1. Open the Azure Portal.
  2. Click “Create a resource” and select “Storage account.”
  3. Specify the subscription and resource group. 
  4. Specify the name and location for the storage account. 
  5. Accept the default values for performance (“Standard”), account kind (“StorageV2”), replication (“RA-GRS”), and access tier (“Hot”).
  6. Click the “Next: Advanced >” button. 
  7. Specify the details as necessary in the “Advanced” and “Tags” tabs (the defaults are OK for our purposes). 
  8. Click “Next: Review + Create” to create the storage account. 
azure table storage figure 2 IDG

The final step in creating your Azure storage account—review the settings and click Create.

Now that your Azure storage account has been created, you can use it to work with Azure Tables.

Create a new Azure Table using C#

Select the console project you created earlier and add the following two NuGet packages from the NuGet package manager.

WindowsAzure.Storage
Microsoft.WindowsAzure.ConfigurationManager

The following code snippet illustrates how you can connect to the Azure storage account we created above and then create a storage table if it doesn’t exist.

static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.AppSettings.Get("TableStorageConnectionString");
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
            CloudTable cloudTable = cloudTableClient.GetTableReference("DemoTable");
            cloudTable.CreateIfNotExists();
            Console.ReadKey();
        }

When you execute the above code, a new table named DemoTable will be created if none exists. You can log into your Azure account and view the table you’ve just created from the Azure Storage Explorer, which is available as a free download for Windows, MacOS, and Linux.

Create an entity in an Azure Table using C#

Inside an Azure Table, you store entities. An entity must have three mandatory properties, namely PartitionKey, RowKey, and Timestamp. To create an entity class, you should create a class that extends the TableEntity class pertaining to the Microsoft.WindowsAzure.Storage namespace. Here is an example of a typical entity. 

public class AuthorEntity : TableEntity
    {
        public AuthorEntity(int id, string firstName, string lastName)
        {
            Id = id;
            FirstName = firstName;
            LastName = lastName;
            PartitionKey = id.ToString();
            RowKey = firstName + lastName;
        }
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

The following code snippet illustrates how you can store the entity in the Azure Table.

static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.AppSettings.Get("TableStorageConnectionString"); 
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
            CloudTable cloudTable = cloudTableClient.GetTableReference("DemoTable");
            cloudTable.CreateIfNotExists();
            var author = new AuthorEntity(1, "Joydip", "Kanjilal");
            TableOperation tableOperation = TableOperation.Insert(author);
            cloudTable.Execute(tableOperation);
            Console.ReadKey();
        }

Read an entity from an Azure Table using C#

To retrieve an entity, you will need to acquire a CloudTable reference and then use it to call the Execute method to run the TableOperation. The following code snippet illustrates how you can read data from Azure Table storage. Note the usage of the TableOperation.Retrieve method.

string connectionString = ConfigurationManager.AppSettings.Get("TableStorageConnectionString"); 
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient cloudTableClient = cloudStorageAccount.CreateCloudTableClient();
CloudTable cloudTable = cloudTableClient.GetTableReference("DemoTable");
TableOperation tableOp = TableOperation.Retrieve<AuthorEntity>("3", "JoydipKanjilal");
TableResult tr = cloudTable.Execute(tableOp);           
var data = tr.Result as AuthorEntity;

Update an entity in an Azure Table using C#

To update an entity in an Azure Table, you will first need to retrieve an instance of TableOperation as shown in the code snippet below.

var partitionKey = "1";
var rowKey = "JoydipKanjilal";
TableOperation tableOp = TableOperation.Retrieve<AuthorEntity>(partitionKey, rowKey);

Next, you should execute the table operation and retrieve the entity instance as shown in this code snippet.

TableResult result = cloudTable.Execute(tableOp);
var data = result.Result as AuthorEntity;

Now that you have retrieved the entity instance, you write your code to update the entity and invoke the Replace method of TableOperation class to update the entity as shown below.

TableResult result = cloudTable.Execute(tableOp);
var data = result.Result as AuthorEntity;
//Write code here to update the author entity.  
if (result != null)
{
     TableOperation updateOp = TableOperation.Replace(data);
     cloudTable.Execute(updateOp);
}

Delete an entity from an Azure Table using C#

To delete an entity, you follow the same approach as when updating an entity except that you will need to call the Delete method on the TableOperation class.

var partitionKey = "1";
var rowKey = "JoydipKanjilal";
TableOperation tableOp = TableOperation.Retrieve<AuthorEntity>(partitionKey, rowKey);
TableResult result = cloudTable.Execute(tableOp);
var data = result.Result as AuthorEntity;    
if (result != null)
 {
    TableOperation deleteOp = TableOperation.Delete(data);
    cloudTable.Execute(deleteOp);
 }

In Microsoft Azure jargon, a table implies a group of entities. Azure Table storage enables you to store and manage entities. In Azure Table storage, an entity is a row of data and a table is a group of entities. While there is no strict limit on the number of tables you may have or the amount of data that a table may contain, Microsoft provides Azure storage scale targets for optimal performance. The Azure Table storage scale targets list 500TB as the maximum size for a table and 1MB as the maximum size for an entity.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author