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 NoSQL 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

Prerequisite check

  • In a terminal or command window, run dotnet --list-sdks to check that .NET 6.x is one of the available versions.
  • Run az --version (Azure CLI) or Get-Module -ListAvailable AzureRM (Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.

Setting up

This section walks you through how to create an Azure Cosmos DB account and set up a project that uses the API for Table NuGet packages.

Create an Azure Cosmos DB account

This quickstart will create a single Azure Cosmos DB account using the API for Table.

  1. Create shell variables for accountName, resourceGroupName, and location.

    # Variable for resource group name
    resourceGroupName="msdocs-cosmos-quickstart-rg"
    location="westus"
    
    # Variable for account name with a randomnly generated suffix
    let suffix=$RANDOM*$RANDOM
    accountName="msdocs-$suffix"
    
  2. If you haven't already, sign in to the Azure CLI using the az login command.

  3. Use the az group create command to create a new resource group in your subscription.

    az group create \
        --name $resourceGroupName \
        --location $location
    
  4. Use the az cosmosdb create command to create a new Azure Cosmos DB for Table account with default settings.

    az cosmosdb create \
        --resource-group $resourceGroupName \
        --name $accountName \
        --locations regionName=$location
        --capabilities EnableTable
    

Get API for Table connection string

  1. Find the API for Table connection string from the list of connection strings for the account with the az cosmosdb list-connection-strings command.

    az cosmosdb list-connection-strings \
        --resource-group $resourceGroupName \
        --name $accountName 
    
  2. Record the Primary Table Connection String values. You'll use these credentials later.

Create a new .NET app

Create a new .NET application in an empty folder using your preferred terminal. Use the dotnet new console to create a new console app.

dotnet new console --output <app-name>

Install the NuGet package

Add the Azure.Data.Tables NuGet package to the new .NET project. Use the dotnet add package command specifying the name of the NuGet package.

dotnet add package Azure.Data.Tables

Configure environment variables

To use the CONNECTION STRING values within your code, set this value on the local machine running the application. To set the environment variable, use your preferred terminal to run the following commands:

$env:COSMOS_CONNECTION_STRING = "<cosmos-connection-string>"

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 TableEntity.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.