Introduction to Azure Table Storage

Azure Table Storage is a NoSQL key-attribute store that is schema-less, making it ideal for storing large amounts of unstructured and semi-structured data. This page provides practical sample code snippets to help you get started with common operations.

We will demonstrate operations using the Azure SDK for .NET, which is a widely used and robust choice for interacting with Azure services.

Prerequisites

Before you begin, ensure you have the following:

  • An Azure Subscription.
  • An Azure Storage Account.
  • The Azure SDK for .NET installed.
  • A reference to the Azure.Data.Tables NuGet package in your project.
Note: For quick testing, you can use connection strings. In production, consider using Azure Identity for more secure authentication.

Creating an Entity

Entities are stored in tables. An entity is a set of properties, analogous to a row in a database. Each entity must have a PartitionKey and a RowKey, which together form its unique identifier.

Here's how to create a simple entity:

// Replace with your actual connection string
string connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
string tableName = "MySampleTable";

// Create a TableServiceClient using the connection string
TableServiceClient tableServiceClient = new TableServiceClient(connectionString);

// Get a reference to the table, creating it if it doesn't exist
TableClient tableClient = await tableServiceClient.CreateTableIfNotExistsAsync(tableName);

// Define an entity
var customer = new
{
    PartitionKey = "Contoso",
    RowKey = "001",
    Name = "Alice Smith",
    Email = "alice.smith@contoso.com",
    Age = 30
};

// Add the entity to the table
await tableClient.UpsertEntityAsync(BinaryData.FromObjectAsJson(customer), TableUpdateMode.Replace);

Console.WriteLine("Entity created successfully!");
C#

Reading a Single Entity

You can retrieve a single entity by providing its PartitionKey and RowKey.

// Assuming you have a TableClient instance as above
string partitionKey = "Contoso";
string rowKey = "001";

// Get the entity
Response response = await tableClient.GetEntityAsync(partitionKey, rowKey);
MyEntity customer = response.Value;

Console.WriteLine($"Name: {customer.Name}, Email: {customer.Email}, Age: {customer.Age}");

// Define a simple class to map the entity properties
public class MyEntity
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
    // ETag and Timestamp are automatically managed by Azure
    public string ETag { get; set; }
    public DateTimeOffset Timestamp { get; set; }
}
C#

Querying Entities

You can query for entities based on various criteria. This is powerful for retrieving specific subsets of your data.

Query by Partition Key

// Query for all entities in the "Contoso" partition
var queryResults = tableClient.Query(e => e.PartitionKey == "Contoso");

foreach (MyEntity entity in queryResults)
{
    Console.WriteLine($"Found: {entity.Name}");
}
C#

Query with Filter (OData Filter Syntax)

You can filter entities using OData filter syntax. For example, finding customers older than 25.

string filter = "Age gt 25";
var filteredResults = tableClient.Query(filter: filter);

foreach (MyEntity entity in filteredResults)
{
    Console.WriteLine($"Found: {entity.Name} (Age: {entity.Age})");
}
C#

Querying with Partition Key and Filter

string partitionKeyFilter = "PartitionKey eq 'Contoso'";
string ageFilter = "Age gt 25";
string combinedFilter = $"{partitionKeyFilter} and {ageFilter}";

var combinedQueryResults = tableClient.Query(filter: combinedFilter);

foreach (MyEntity entity in combinedQueryResults)
{
    Console.WriteLine($"Found: {entity.Name} (Age: {entity.Age})");
}
C#

Updating an Entity

To update an entity, you typically retrieve it, modify its properties, and then submit the changes. You can use UpsertEntityAsync or UpdateEntityAsync.

// Retrieve the entity to update
Response response = await tableClient.GetEntityAsync("Contoso", "001");
MyEntity customerToUpdate = response.Value;

// Modify properties
customerToUpdate.Age = 31;
customerToUpdate.Email = "alice.smith.updated@contoso.com";

// Update the entity in the table.
// TableUpdateMode.Merge will only update specified properties,
// while TableUpdateMode.Replace will replace the entire entity.
await tableClient.UpsertEntityAsync(BinaryData.FromObjectAsJson(customerToUpdate), TableUpdateMode.Replace);

Console.WriteLine("Entity updated successfully!");
C#

Deleting an Entity

Deleting an entity is straightforward using its PartitionKey and RowKey.

// Assuming you have the partitionKey and rowKey
string partitionKeyToDelete = "Contoso";
string rowKeyToDelete = "001";

await tableClient.DeleteEntityAsync(partitionKeyToDelete, rowKeyToDelete);

Console.WriteLine("Entity deleted successfully!");
C#

Performing Batch Operations

Azure Table Storage supports batch operations, allowing you to perform multiple insert, update, or delete operations in a single request. This is crucial for transactional consistency within a single partition.

// Create a list of operations
var batchOperations = new List();

// Example: Insert two entities and update one
var entity1 = new
{
    PartitionKey = "Logs",
    RowKey = Guid.NewGuid().ToString(),
    Message = "Application started",
    Timestamp = DateTimeOffset.UtcNow
};
batchOperations.Add(new TableTransactionAction(TableTransactionActionType.Add, BinaryData.FromObjectAsJson(entity1)));

var entity2 = new
{
    PartitionKey = "Logs",
    RowKey = Guid.NewGuid().ToString(),
    Message = "User logged in",
    Username = "Alice",
    Timestamp = DateTimeOffset.UtcNow
};
batchOperations.Add(new TableTransactionAction(TableTransactionActionType.Add, BinaryData.FromObjectAsJson(entity2)));

// Example: Retrieve and update an entity (requires separate GetEntityAsync call before creating the batch)
// Assume 'entityToUpdate' is retrieved from a previous GetEntityAsync call
// customerToUpdate.Age = 32;
// batchOperations.Add(new TableTransactionAction(TableTransactionActionType.UpdateMerge, BinaryData.FromObjectAsJson(customerToUpdate)));


try
{
    // Submit the batch
    Response> response = await tableClient.SubmitTransactionAsync(batchOperations);
    Console.WriteLine("Batch operation completed successfully.");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Batch operation failed: {ex.Message}");
}
C#
Important: Batch operations must operate on entities within the same PartitionKey.

Explore Further

Dive deeper into the capabilities of Azure Table Storage and its SDKs.

Azure Table Storage Documentation Azure SDK for .NET Table API