Quickstart: Azure Cosmos DB for Table for .NET

APPLIES TO: Table

This quickstart shows how to get started with the Azure Cosmos DB for Table from a .NET application. The Azure Cosmos DB for Table is a schemaless data store allowing applications to store structured table data in the cloud. You'll learn how to create tables, rows, and perform basic tasks within your Azure Cosmos DB resource using the Azure.Data.Tables Package (NuGet).

Note

The example code snippets are available on GitHub as a .NET project.

API for Table reference documentation | Azure.Data.Tables Package (NuGet)

Prerequisites

Setting up

Deploy this project's development container to your environment. Then, use the Azure Developer CLI (azd) to create an Azure Cosmos DB for Table account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.

Open in GitHub Codespaces

Open in Dev Container

Important

GitHub accounts include an entitlement of storage and core hours at no cost. For more information, see included storage and core hours for GitHub accounts.

  1. Open a terminal in the root directory of the project.

  2. Authenticate to the Azure Developer CLI using azd auth login. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.

    azd auth login
    
  3. Use azd init to initialize the project.

    azd init
    
  4. During initialization, configure a unique environment name.

    Tip

    The environment name will also be used as the target resource group name. For this quickstart, consider using msdocs-cosmos-db.

  5. Deploy the Azure Cosmos DB account using azd up. The Bicep templates also deploy a sample web application.

    azd up
    
  6. During the provisioning process, select your subscription and desired location. Wait for the provisioning process to complete. The process can take approximately five minutes.

  7. Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.

    Deploying services (azd deploy)
    
      (✓) Done: Deploying service web
    - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
    
    SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
    
  8. Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.

    Screenshot of the running web application.

Install the client library

The client library is available through NuGet, as the Microsoft.Azure.Cosmos package.

  1. Open a terminal and navigate to the /src/web folder.

    cd ./src/web
    
  2. If not already installed, install the Azure.Data.Tables package using dotnet add package.

    dotnet add package Azure.Data.Tables
    
  3. Also, install the Azure.Identity package if not already installed.

    dotnet add package Azure.Identity
    
  4. Open and review the src/web/Cosmos.Samples.Table.Quickstart.Web.csproj file to validate that the Microsoft.Azure.Cosmos and Azure.Identity entries both exist.

Code examples

The sample code described in this article creates a table named adventureworks. Each table row contains the details of a product such as name, category, quantity, and a sale indicator. Each product also contains a unique identifier.

You'll use the following API for Table classes to interact with these resources:

  • TableServiceClient - This class provides methods to perform service level operations with Azure Cosmos DB for Table.
  • TableClient - This class allows you to interact with tables hosted in the Azure Cosmos DB table API.
  • TableEntity - This class is a reference to a row in a table that allows you to manage properties and column data.

Authenticate the client

From the project directory, open the Program.cs file. In your editor, add a using directive for Azure.Data.Tables.

using Azure.Data.Tables;

Define a new instance of the TableServiceClient class using the constructor, and Environment.GetEnvironmentVariable to read the connection string you set earlier.

// New instance of the TableClient class
TableServiceClient tableServiceClient = new TableServiceClient(Environment.GetEnvironmentVariable("COSMOS_CONNECTION_STRING"));

Create a table

Retrieve an instance of the TableClient using the TableServiceClient class. Use the TableClient.CreateIfNotExistsAsync method on the TableClient to create a new table if it doesn't already exist. This method will return a reference to the existing or newly created table.

// New instance of TableClient class referencing the server-side table
TableClient tableClient = tableServiceClient.GetTableClient(
    tableName: "adventureworks"
);

await tableClient.CreateIfNotExistsAsync();

Create an item

The easiest way to create a new item in a table is to create a class that implements the ITableEntity interface. You can then add your own properties to the class to populate columns of data in that table row.

// C# record type for items in the table
public record Product : ITableEntity
{
    public string RowKey { get; set; } = default!;

    public string PartitionKey { get; set; } = default!;

    public string Name { get; init; } = default!;

    public int Quantity { get; init; }

    public bool Sale { get; init; }

    public ETag ETag { get; set; } = default!;

    public DateTimeOffset? Timestamp { get; set; } = default!;
}

Create an item in the collection using the Product class by calling TableClient.AddEntityAsync<T>.

// Create new item using composite key constructor
var prod1 = new Product()
{
    RowKey = "68719518388",
    PartitionKey = "gear-surf-surfboards",
    Name = "Ocean Surfboard",
    Quantity = 8,
    Sale = true
};

// Add new item to server-side table
await tableClient.AddEntityAsync<Product>(prod1);

Get an item

You can retrieve a specific item from a table using the TableClient.GetEntityAsync<T> method. Provide the partitionKey and rowKey as parameters to identify the correct row to perform a quick point read of that item.

// Read a single item from container
var product = await tableClient.GetEntityAsync<Product>(
    rowKey: "68719518388",
    partitionKey: "gear-surf-surfboards"
);
Console.WriteLine("Single product:");
Console.WriteLine(product.Value.Name);

Query items

After you insert an item, you can also run a query to get all items that match a specific filter by using the TableClient.Query<T> method. This example filters products by category using Linq syntax, which is a benefit of using typed ITableEntity models like the Product class.

Note

You can also query items using OData syntax. You can see an example of this approach in the Query Data tutorial.

// Read multiple items from container
var prod2 = new Product()
{
    RowKey = "68719518390",
    PartitionKey = "gear-surf-surfboards",
    Name = "Sand Surfboard",
    Quantity = 5,
    Sale = false
};

await tableClient.AddEntityAsync<Product>(prod2);

var products = tableClient.Query<Product>(x => x.PartitionKey == "gear-surf-surfboards");

Console.WriteLine("Multiple products:");
foreach (var item in products)
{
    Console.WriteLine(item.Name);
}

Run the code

This app creates an Azure Cosmos DB Table API table. The example then creates an item and then reads the exact same item back. Finally, the example creates a second item and then performs a query that should return multiple items. With each step, the example outputs metadata to the console about the steps it has performed.

To run the app, use a terminal to navigate to the application directory and run the application.

dotnet run

The output of the app should be similar to this example:

Single product name: 
Yamba Surfboard
Multiple products:
Yamba Surfboard
Sand Surfboard

Clean up resources

When you no longer need the Azure Cosmos DB for Table account, you can delete the corresponding resource group.

Use the az group delete command to delete the resource group.

az group delete --name $resourceGroupName

Next steps

In this quickstart, you learned how to create an Azure Cosmos DB for Table account, create a table, and manage entries using the .NET SDK. You can now dive deeper into the SDK to learn how to perform more advanced data queries and management tasks in your Azure Cosmos DB for Table resources.