Quickstart: Build a Table API app with .NET SDK and Azure Cosmos DB


This quickstart shows how to use .NET and the Azure Cosmos DB Table API to build an app by cloning an example from GitHub. This quickstart also shows you how to create an Azure Cosmos DB account and how to use Data Explorer to create tables and entities in the web-based Azure portal.


If you don’t already have Visual Studio 2019 installed, you can download and use the free Visual Studio 2019 Community Edition. Make sure that you enable Azure development during the Visual Studio setup.

If you don't have an Azure subscription, create a free account before you begin.

Create a database account

  1. In a new browser window, sign in to the Azure portal.

  2. In the left menu, select Create a resource.

    Create a resource in the Azure portal

  3. On the New page, select Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  4. On the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    Setting Value Description
    Subscription Your subscription Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    Resource Group Create new, then Account Name Select Create new. Then enter a new resource group name for your account. For simplicity, use the same name as your Azure Cosmos DB account name.
    Account Name A unique name Enter a unique name to identify your Azure Cosmos DB account.

    The account name can use only lowercase letters, numbers, and hyphens (-), and must be between 3 and 31 characters long.
    API Table The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, MongoDB for document databases, Azure Table, and Cassandra. You must create a separate account for each API.

    Select Azure Table, because in this quickstart you are creating a table that works with the Table API.

    Learn more about the Table API.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that's closest to your users to give them the fastest access to the data.
    Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode.

    You can leave the Geo-Redundancy and Multi-region Writes options at Disable to avoid additional charges, and skip the Network and Tags sections.

  5. Select Review+Create. After the validation is complete, select Create to create the account.

    The new account page for Azure Cosmos DB

  6. It takes a few minutes to create the account. You'll see a message that states Your deployment is underway. Wait for the deployment to finish, and then select Go to resource.

    The Azure portal notifications pane

Add a table

You can now use the Data Explorer tool in the Azure portal to create a database and table.

  1. Select Data Explorer > New Table.

    The Add Table area is displayed on the far right, you may need to scroll right to see it.

    Data Explorer in the Azure portal

  2. In the Add Table page, enter the settings for the new table.

    Setting Suggested value Description
    Table Id sample-table The ID for your new table. Table names have the same character requirements as database ids. Database names must be between 1 and 255 characters, and cannot contain / \ # ? or a trailing space.
    Throughput 400 RUs Change the throughput to 400 request units per second (RU/s). If you want to reduce latency, you can scale up the throughput later.
  3. Select OK.

  4. Data Explorer displays the new database and table.

    The Azure portal Data Explorer, showing the new database and collection

Add sample data

You can now add data to your new table using Data Explorer.

  1. In Data Explorer, expand sample-table, select Entities, and then select Add Entity.

    Create new entities in Data Explorer in the Azure portal

  2. Now add data to the PartitionKey value box and RowKey value box, and select Add Entity.

    Set the Partition Key and Row Key for a new entity

    You can now add more entities to your table, edit your entities, or query your data in Data Explorer. Data Explorer is also where you can scale your throughput and add stored procedures, user-defined functions, and triggers to your table.

Clone the sample application

Now let's clone a Table app from GitHub, set the connection string, and run it. You'll see how easy it is to work with data programmatically.

  1. Open a command prompt, create a new folder named git-samples, then close the command prompt.

    md "C:\git-samples"
  2. Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
  3. Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-cosmos-table-dotnet-core-getting-started.git


For a more detailed walkthrough of similar code, see the Cosmos DB Table API sample article.

Open the sample application in Visual Studio

  1. In Visual Studio, from the File menu, choose Open, then choose Project/Solution.

    Open the solution

  2. Navigate to the folder where you cloned the sample application and open the TableStorage.sln file.

Review the code

This step is optional. If you're interested in learning how the database resources are created in the code, you can review the following snippets. Otherwise, you can skip ahead to update the connection string section of this doc.

  • The following code shows how to create a table within the Azure Storage:

    public static async Task<CloudTable> CreateTableAsync(string tableName)
        string storageConnectionString = AppSettings.LoadAppSettings().StorageConnectionString;
        // Retrieve storage account information from connection string.
        CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString);
        // Create a table client for interacting with the table service
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
        Console.WriteLine("Create a Table for the demo");
        // Create a table client for interacting with the table service 
        CloudTable table = tableClient.GetTableReference(tableName);
        if (await table.CreateIfNotExistsAsync())
            Console.WriteLine("Created Table named: {0}", tableName);
            Console.WriteLine("Table {0} already exists", tableName);
        return table;
  • The following code shows how to insert data into the table:

    public static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        if (entity == null)
            throw new ArgumentNullException("entity");
            // Create the InsertOrReplace table operation
            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);
            // Execute the operation.
            TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            CustomerEntity insertedCustomer = result.Result as CustomerEntity;
            if (result.RequestCharge.HasValue)
                Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
            return insertedCustomer;
        catch (StorageException e)
  • The following code shows how to query data from the table:

    public static async Task<CustomerEntity> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
            TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(partitionKey, rowKey);
            TableResult result = await table.ExecuteAsync(retrieveOperation);
            CustomerEntity customer = result.Result as CustomerEntity;
            if (customer != null)
                Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
            if (result.RequestCharge.HasValue)
                Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
            return customer;
        catch (StorageException e)
  • The following code shows how to delete data from the table:

    public static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
            if (deleteEntity == null)
                throw new ArgumentNullException("deleteEntity");
            TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
            TableResult result = await table.ExecuteAsync(deleteOperation);
            if (result.RequestCharge.HasValue)
                Console.WriteLine("Request Charge of Delete Operation: " + result.RequestCharge);
        catch (StorageException e)

Update your connection string

Now go back to the Azure portal to get your connection string information and copy it into the app. This enables your app to communicate with your hosted database.

  1. In the Azure portal, click Connection String. Use the copy button on the right side of the window to copy the PRIMARY CONNECTION STRING.

    View and copy the PRIMARY CONNECTION STRING in the Connection String pane

  2. In Visual Studio, open the Settings.json file.

  3. Paste the PRIMARY CONNECTION STRING from the portal into the StorageConnectionString value. Paste the string inside the quotes.

       "StorageConnectionString": "<Primary connection string from Azure portal>"
  4. Press CTRL+S to save the Settings.json file.

You've now updated your app with all the info it needs to communicate with Azure Cosmos DB.

Build and deploy the app

  1. In Visual Studio, right-click on the CosmosTableSamples project in Solution Explorer and then click Manage NuGet Packages.

    Manage NuGet Packages

  2. In the NuGet Browse box, type Microsoft.Azure.Cosmos.Table. This will find the Cosmos DB Table API client library. Note that this library is currently available for .NET Framework and .NET Standard.

    NuGet Browse tab

  3. Click Install to install the Microsoft.Azure.Cosmos.Table library. This installs the Azure Cosmos DB Table API package and all dependencies.

  4. When you run the entire app, sample data is inserted into the table entity and deleted at the end so you won’t see any data inserted if you run the whole sample. However you can insert some breakpoints to view the data. Open BasicSamples.cs file and right-click on line 52, select Breakpoint, then select Insert Breakpoint. Insert another breakpoint on line 55.

    Add a breakpoint

  5. Press F5 to run the application. The console window displays the name of the new table database (in this case, demoa13b1) in Azure Cosmos DB.

    Console output

    When you hit the first breakpoint, go back to Data Explorer in the Azure portal. Click the Refresh button, expand the demo* table, and click Entities. The Entities tab on the right shows the new entity that was added for Walter Harp. Note that the phone number for the new entity is 425-555-0101.

    New entity

    If you receive an error that says Settings.json file can’t be found when running the project, you can resolve it by adding the following XML entry to the project settings. Right click on CosmosTableSamples, select Edit CosmosTableSamples.csproj and add the following itemGroup:

        <None Update="Settings.json">
  6. Close the Entities tab in Data Explorer.

  7. Press F5 to run the app to the next breakpoint.

    When you hit the breakpoint, switch back to the Azure portal, click Entities again to open the Entities tab, and note that the phone number has been updated to 425-555-0105.

  8. Press F5 to run the app.

    The app adds entities for use in an advanced sample app that the Table API currently does not support. The app then deletes the table created by the sample app.

  9. In the console window, press Enter to end the execution of the app.

Review SLAs in the Azure portal

The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. This suite of metrics makes monitoring your SLAs transparent.

To review metrics and SLAs:

  1. Select Metrics in your Cosmos DB account's navigation menu.

  2. Select a tab such as Latency, and select a timeframe on the right. Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB metrics suite

  3. Review the metrics on the other tabs.

Clean up resources

When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. To delete the resources:

  1. In the Azure portal Search bar, search for and select Resource groups.

  2. From the list, select the resource group you created for this quickstart.

    Select the resource group to delete

  3. On the resource group Overview page, select Delete resource group.

    Delete the resource group

  4. In the next window, enter the name of the resource group to delete, and then select Delete.

Next steps

In this quickstart, you've learned how to create an Azure Cosmos DB account, create a table using the Data Explorer, and run an app. Now you can query your data using the Table API.