Azure Table storage is a service that stores large amounts of structured NoSQL data in the cloud, providing a key/attribute store with a schema-less design.
Azure Cosmos DB provides a Table API for applications that are written for Azure Table storage that need premium capabilities like:
- Turnkey global distribution.
- Dedicated throughput worldwide.
- Single-digit millisecond latencies at the 99th percentile.
- Guaranteed high availability.
- Automatic secondary indexing.
The Azure Tables client library can seamlessly target either Azure Table storage or Azure Cosmos DB table service endpoints with no code changes.
Source code | Package (NuGet) | API reference documentation | Samples | Change Log
Install the Azure Tables client library for .NET with NuGet:
dotnet add package Azure.Data.Tables
- An Azure subscription.
- An existing Azure storage account or Azure Cosmos DB database with Azure Table API specified.
If you need to create either of these, you can use the Azure CLI.
Create a storage account mystorageaccount
in resource group MyResourceGroup
in the subscription MySubscription
in the West US region.
az storage account create -n mystorageaccount -g MyResourceGroup -l westus --subscription MySubscription
Create a Cosmos DB account MyCosmosDBDatabaseAccount
in resource group MyResourceGroup
in the subscription MySubscription
and a table named MyTableName
in the account.
az cosmosdb create --name MyCosmosDBDatabaseAccount --capabilities EnableTable --resource-group MyResourceGroup --subscription MySubscription
az cosmosdb table create --name MyTableName --resource-group MyResourceGroup --account-name MyCosmosDBDatabaseAccount
Learn more about options for authentication (including Connection Strings, Shared Key, Shared Key Signatures, and TokenCredentials) in our samples.
TableServiceClient
- Client that provides methods to interact at the Table Service level such as creating, listing, and deleting tablesTableClient
- Client that provides methods to interact at an table entity level such as creating, querying, and deleting entities within a table.Table
- Tables store data as collections of entities.Entity
- Entities are similar to rows. An entity has a primary key and a set of properties. A property is a name value pair, similar to a column.
Common uses of the Table service include:
- Storing TBs of structured data capable of serving web scale applications
- Storing datasets that don't require complex joins, foreign keys, or stored procedures and can be de-normalized for fast access
- Quickly querying data using a clustered index
- Accessing data using the OData protocol and LINQ filter expressions
We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.
Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime
First, we need to construct a TableServiceClient
.
// Construct a new "TableServiceClient using a TableSharedKeyCredential.
var serviceClient = new TableServiceClient(
new Uri(storageUri),
new TableSharedKeyCredential(accountName, storageAccountKey));
Next, we can create a new table.
// Create a new table. The TableItem class stores properties of the created table.
string tableName = "OfficeSupplies1p1";
TableItem table = serviceClient.CreateTableIfNotExists(tableName);
Console.WriteLine($"The created table's name is {table.Name}.");
The set of existing Azure tables can be queries using an OData filter.
// Use the <see cref="TableServiceClient"> to query the service. Passing in OData filter strings is optional.
Pageable<TableItem> queryTableResults = serviceClient.Query(filter: $"TableName eq '{tableName}'");
Console.WriteLine("The following are the names of the tables in the query results:");
// Iterate the <see cref="Pageable"> in order to access queried tables.
foreach (TableItem table in queryTableResults)
{
Console.WriteLine(table.Name);
}
Individual tables can be deleted from the service.
// Deletes the table made previously.
string tableName = "OfficeSupplies1p1";
serviceClient.DeleteTable(tableName);
To interact with table entities, we must first construct a TableClient
.
// Construct a new <see cref="TableClient" /> using a <see cref="TableSharedKeyCredential" />.
var tableClient = new TableClient(
new Uri(storageUri),
tableName,
new TableSharedKeyCredential(accountName, storageAccountKey));
// Create the table in the service.
tableClient.Create();
Let's define a new TableEntity
so that we can add it to the table.
// Make a dictionary entity by defining a <see cref="TableEntity">.
var entity = new TableEntity(partitionKey, rowKey)
{
{ "Product", "Marker Set" },
{ "Price", 5.00 },
{ "Quantity", 21 }
};
Console.WriteLine($"{entity.RowKey}: {entity["Product"]} costs ${entity.GetDouble("Price")}.");
Using the TableClient
we can now add our new entity to the table.
// Add the newly created entity.
tableClient.AddEntity(entity);
To inspect the set of existing table entities, we can query the table using an OData filter.
Pageable<TableEntity> queryResultsFilter = tableClient.Query<TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");
// Iterate the <see cref="Pageable"> to access all queried entities.
foreach (TableEntity qEntity in queryResultsFilter)
{
Console.WriteLine($"{qEntity.GetString("Product")}: {qEntity.GetDouble("Price")}");
}
Console.WriteLine($"The query returned {queryResultsFilter.Count()} entities.");
If you prefer LINQ style query expressions, we can query the table using that syntax as well.
double priceCutOff = 6.00;
Pageable<OfficeSupplyEntity> queryResultsLINQ = tableClient.Query<OfficeSupplyEntity>(ent => ent.Price >= priceCutOff);
If we no longer need our new table entity, it can be deleted.
// Delete the entity given the partition and row key.
tableClient.DeleteEntity(partitionKey, rowKey);
When you interact with the Azure table library using the .NET SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests.
For example, if you try to create a table that already exists, a 409
error is returned, indicating "Conflict".
// Construct a new TableClient using a connection string.
var client = new TableClient(
connectionString,
tableName);
// Create the table if it doesn't already exist.
client.CreateIfNotExists();
// Now attempt to create the same table unconditionally.
try
{
client.Create();
}
catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict)
{
Console.WriteLine(ex.ToString());
}
The simplest way to see the logs is to enable the console logging. To create an Azure SDK log listener that outputs messages to console use AzureEventSourceListener.CreateConsoleLogger method.
// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
To learn more about other logging mechanisms see here.
Get started with our Table samples.
A list of currently known issues relating to Cosmos DB table endpoints can be found here.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit cla.microsoft.com.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.