Build a .NET console app to manage data in Azure Cosmos DB SQL API account

Welcome to the Azure Cosmos DB SQL API get started tutorial. After following this tutorial, you'll have a console application that creates and queries Azure Cosmos DB resources. This tutorial uses Version 3.0+ of the Azure Cosmos DB .NET SDK, which can be targeted to .NET Framework or .NET Core.

This tutorial covers:

  • Creating and connecting to an Azure Cosmos account
  • Configuring your project in Visual Studio
  • Creating a database and a container
  • Adding items to the container
  • Querying the container
  • CRUD operations on the item
  • Deleting the database

Don't have time? Don't worry! The complete solution is available on GitHub. Jump to the Get the complete tutorial solution section for quick instructions.

Now let's get started!

Prerequisites

Step 1: Create an Azure Cosmos DB account

Let's create an Azure Cosmos DB account. If you already have an account you want to use, you can skip ahead to Setup your Visual Studio Solution. If you are using the Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to setup the emulator and skip ahead to Setup your Visual Studio project.

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

  2. Click Create a resource > Databases > Azure Cosmos DB.

    The Azure portal Databases pane

  3. In 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

    Enter a unique name
    Select Create New, then enter a new resource-group name for your account. For simplicity, you can use the same name as your Account Name.
    Account Name Enter a unique name Enter a unique name to identify your Azure Cosmos DB account. Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    The ID can only contain lowercase letters, numbers, and the hyphen (-) character, and it must be between 3 and 31 characters in length..
    API Core (SQL) The API determines the type of account to create. Azure Cosmos DB provides five APIs: SQL (document database), Gremlin (graph database), MongoDB (document database), Table API, and Cassandra API. Each API currently requires you to create a separate account.

    Select Core (SQL) because in this article you will create a document database and query using SQL syntax.

    Learn more about the SQL API
    Location Select 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.
    Enable geo-redundancy Leave blank This creates a replicated version of your database in a second (paired) region. Leave this blank.
    Multi-region writes Leave blank This enables each of your database regions to be both a read and write region. Leave this blank.

    Then click Review + create. You can skip the Network and Tags section.

    The new account page for Azure Cosmos DB

    Review the summary information and click Create.

    The account verification summary page

  4. The account creation takes a few minutes. Wait for the portal to display the Your deployment is complete message and click Go to resource.

    The account successfully created page

  5. The portal will now display the Congratulations! Your Azure Cosmos DB account was created page.

    The Azure portal Notifications pane

Step 2: Setup your Visual Studio project

  1. Open Visual Studio 2017 on your computer.

  2. On the File menu, select New, and then choose Project.

  3. In the New Project dialog, select Visual C# / Console App (.NET Framework), name your project, and then click OK. Screenshot of the New Project window

    Note

    For .NET core target, in the New Project dialog, select Visual C# / Console App (.NET Core), name your project, and then click OK

  4. In the Solution Explorer, right click on your new console application, which is under your Visual Studio solution, and then click Manage NuGet Packages...

    Screenshot of the Right Clicked Menu for the Project

  5. In the NuGet tab, click Browse, and type Microsoft.Azure.Cosmos in the search box.

  6. Within the results, find Microsoft.Azure.Cosmos and click Install. The package ID for the Azure Cosmos DB SQL API Client Library is Microsoft Azure Cosmos DB Client Library. Screenshot of the NuGet Menu for finding Azure Cosmos DB Client SDK

    If you get a message about reviewing changes to the solution, click OK. If you get a message about license acceptance, click I accept.

Great! Now that we finished the setup, let's start writing some code. You can find a completed code project of this tutorial at GitHub.

Step 3: Connect to an Azure Cosmos DB account

  1. First, replace the references at the beginning of your C# application, in the Program.cs file with these references:

    using System;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Net;
    using Microsoft.Azure.Cosmos;
    
  2. Now, add these constants and variables into your public class Program.

    public class Program
    {
        // ADD THIS PART TO YOUR CODE
    
        // The Azure Cosmos DB endpoint for running this sample.
        private static readonly string EndpointUri = "<your endpoint here>";
        // The primary key for the Azure Cosmos account.
        private static readonly string PrimaryKey = "<your primary key>";
    
        // The Cosmos client instance
        private CosmosClient cosmosClient;
    
        // The database we will create
        private Database database;
    
        // The container we will create.
        private Container container;
    
        // The name of the database and container we will create
        private string databaseId = "FamilyDatabase";
        private string containerId = "FamilyContainer";
    }
    

    Note, if you are familiar with the previous version of the .NET SDK, you may be used to seeing the terms 'collection' and 'document.' Because Azure Cosmos DB supports multiple API models, version 3.0+ of the .NET SDK uses the generic terms 'container' and 'item.' A container can be a collection, graph, or table. An item can be a document, edge/vertex, or row, and is the content inside a container. Learn more about databases, containers, and items.

  3. Retrieve your endpoint URL and primary key from the Azure portal.

    In the Azure portal, navigate to your Azure Cosmos DB account, and then click Keys.

    Copy the URI from the portal and paste it into <your endpoint URL> in the Program.cs file. Copy the PRIMARY KEY from the portal and paste it into <your primary key>.

    Screenshot to get Azure Cosmos DB keys from Azure portal

  4. Next, we'll create a new instance of CosmosClient and set up some scaffolding for our program.

    Below the Main method, add a new asynchronous task called GetStartedDemoAsync, which will instantiate our new CosmosClient. We will use GetStartedDemoAsync as the entry point that calls methods that operate on Azure Cosmos DB resources.

    public static async Task Main(string[] args)
    {
    }
    
    // ADD THIS PART TO YOUR CODE
    /*
        Entry point to call methods that operate on Azure Cosmos DB resources in this sample
    */
    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    }
    
  5. Add the following code to run the GetStartedDemoAsync asynchronous task from your Main method. The Main method will catch exceptions and write them to the console.

    public static async Task Main(string[] args)
    {
        try
        {
            Console.WriteLine("Beginning operations...\n");
            Program p = new Program();
            await p.GetStartedDemoAsync();
    
        }
        catch (CosmosException de)
        {
            Exception baseException = de.GetBaseException();
            Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
        }
        finally
        {
            Console.WriteLine("End of demo, press any key to exit.");
            Console.ReadKey();
        }
    }
    
  6. Select F5 to run your application. The console window output displays the message End of demo, press any key to exit. confirming that the connection to Azure Cosmos DB was made. You can then close the console window.

Congratulations! You have successfully connected to an Azure Cosmos DB account.

Step 4: Create a database

A database can be created by using either the CreateDatabaseIfNotExistsAsync or CreateDatabaseAsync function of the CosmosClient class. A database is the logical container of items partitioned across containers.

  1. Copy and paste the CreateDatabaseAsync method below your GetStartedDemoAsync method. CreateDatabaseAsync will create a new database with ID FamilyDatabase if it does not already exist, with the ID specified from the databaseId field.

    /// <summary>
    /// Create the database if it does not exist
    /// </summary>
    private async Task CreateDatabaseAsync()
    {
        // Create a new database
        this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
        Console.WriteLine("Created Database: {0}\n", this.database.Id);
    }
    
  2. Copy and paste the code below where you instantiated the CosmosClient to call the CreateDatabaseAsync method you just added.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
    
        //ADD THIS PART TO YOUR CODE
        await this.CreateDatabaseAsync();
    }
    

    At this point, your code should now look like this, with your endpoint and primary key filled in.

    using System;
    using System.Threading.Tasks;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Net;
    using Microsoft.Azure.Cosmos;
    
    namespace CosmosGettingStarted
    {
        class Program
        {
            // The Azure Cosmos DB endpoint for running this sample.
            private static readonly string EndpointUri = "<your endpoint here>";
            // The primary key for the Azure Cosmos account.
            private static readonly string PrimaryKey = "<your primary key>";
    
            // The Cosmos client instance
            private CosmosClient cosmosClient;
    
            // The database we will create
            private Database database;
    
            // The container we will create.
            private Container container;
    
            // The name of the database and container we will create
            private string databaseId = "FamilyDatabase";
            private string containerId = "FamilyContainer";
    
            public static async Task Main(string[] args)
            {
                try
                {
                    Console.WriteLine("Beginning operations...");
                    Program p = new Program();
                    await p.GetStartedDemoAsync();
                }
                catch (CosmosException de)
                {
                    Exception baseException = de.GetBaseException();
                    Console.WriteLine("{0} error occurred: {1}\n", de.StatusCode, de);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}\n", e);
                }
                finally
                {
                    Console.WriteLine("End of demo, press any key to exit.");
                    Console.ReadKey();
                }
            }
    
            /// <summary>
            /// Entry point to call methods that operate on Azure Cosmos DB resources in this sample
            /// </summary>
            public async Task GetStartedDemoAsync()
            {
                // Create a new instance of the Cosmos Client
                this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
                await this.CreateDatabaseAsync();
            }
    
            /// <summary>
            /// Create the database if it does not exist
            /// </summary>
            private async Task CreateDatabaseAsync()
            {
                // Create a new database
                this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(databaseId);
                Console.WriteLine("Created Database: {0}\n", this.database.Id);
            }
        }
    }
    

Select F5 to run your application.

Congratulations! You have successfully created an Azure Cosmos DB database.

Step 5: Create a container

Warning

Calling the method CreateContainerIfNotExistsAsync will create a new container, which has pricing implications. For more details, please visit our pricing page.

A container can be created by using either the CreateContainerIfNotExistsAsync or CreateContainerAsync function in the CosmosDatabase class. A container consists of items (JSON documents if SQL API) and associated server-side application logic in JavaScript, for example, stored procedures, user-defined functions, and triggers.

  1. Copy and paste the CreateContainerAsync method below your CreateDatabaseAsync method. CreateContainerAsync will create a new container with ID FamilyContainer if it does not already exist, with the ID specified from the containerId field partitioned by LastName property.

    /// <summary>
    /// Create the container if it does not exist. 
    /// Specifiy "/LastName" as the partition key since we're storing family information, to ensure good distribution of requests and storage.
    /// </summary>
    /// <returns></returns>
    private async Task CreateContainerAsync()
    {
        // Create a new container
        this.container = await this.database.CreateContainerIfNotExistsAsync(containerId, "/LastName");
        Console.WriteLine("Created Container: {0}\n", this.container.Id);
    }
    
  2. Copy and paste the code below where you instantiated the CosmosClient to call the CreateContainer method you just added.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.CreateContainerAsync();
    }
    

    Select F5 to run your application.

Congratulations! You have successfully created an Azure Cosmos DB container.

Step 6: Add items to the container

An item can be created by using the CreateItemAsync function of the CosmosContainer class. When using the SQL API, items are projected as documents, which are user-defined (arbitrary) JSON content. You can now insert an item into your Azure Cosmos DB container.

First, let's create a Family class that will represent objects stored within Azure Cosmos DB in this sample. We will also create Parent, Child, Pet, Address subclasses that are used within Family. Note item must have an Id property serialized as id in JSON.

  1. Select Ctrl+Shift+A to open the Add New Item dialog. Add a new class Family.cs to your project.

    Screenshot of adding a new Family.cs class into the project

  2. Copy and paste the Family, Parent, Child, Pet, and Address class into Family.cs.

    using Newtonsoft.Json;
    
    namespace CosmosGettingStartedTutorial
    {
        public class Family
        {
            [JsonProperty(PropertyName = "id")]
            public string Id { get; set; }
            public string LastName { get; set; }
            public Parent[] Parents { get; set; }
            public Child[] Children { get; set; }
            public Address Address { get; set; }
            public bool IsRegistered { get; set; }
            public override string ToString()
            {
                return JsonConvert.SerializeObject(this);
            }
        }
    
        public class Parent
        {
            public string FamilyName { get; set; }
            public string FirstName { get; set; }
        }
    
        public class Child
        {
            public string FamilyName { get; set; }
            public string FirstName { get; set; }
            public string Gender { get; set; }
            public int Grade { get; set; }
            public Pet[] Pets { get; set; }
        }
    
        public class Pet
        {
            public string GivenName { get; set; }
        }
    
        public class Address
        {
            public string State { get; set; }
            public string County { get; set; }
            public string City { get; set; }
        }
    }
    
  3. Navigate back to Program.cs and add the AddItemsToContainerAsync method under your CreateContainerAsync method. The code checks to make sure an item with the same ID does not already exist before creating it. We will insert two items, one each for the Andersen Family and the Wakefield Family.

    /// <summary>
    /// Add Family items to the container
    /// </summary>
    private async Task AddItemsToContainerAsync()
    {
        // Create a family object for the Andersen family
        Family andersenFamily = new Family
        {
            Id = "Andersen.1",
            LastName = "Andersen",
            Parents = new Parent[]
            {
                new Parent { FirstName = "Thomas" },
                new Parent { FirstName = "Mary Kay" }
            },
            Children = new Child[]
            {
                new Child
                {
                    FirstName = "Henriette Thaulow",
                    Gender = "female",
                    Grade = 5,
                    Pets = new Pet[]
                    {
                        new Pet { GivenName = "Fluffy" }
                    }
                }
            },
            Address = new Address { State = "WA", County = "King", City = "Seattle" },
            IsRegistered = false
        };
    
        try
        {
            // Read the item to see if it exists. Note ReadItemAsync will not throw an exception if an item does not exist. Instead, we check the StatusCode property off the response object. 
            ItemResponse<Family> andersenFamilyResponse = await this.container.ReadItemAsync<Family>(andersenFamily.Id, new PartitionKey(andersenFamily.LastName));
            Console.WriteLine("Item in database with id: {0} already exists\n", andersenFamilyResponse.Resource.Id);
        }
        catch(CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            // Create an item in the container representing the Andersen family. Note we provide the value of the partition key for this item, which is "Andersen"
            ItemResponse<Family> andersenFamilyResponse = await this.container.CreateItemAsync<Family>(andersenFamily, new PartitionKey(andersenFamily.LastName));
    
            // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
            Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", andersenFamilyResponse.Resource.Id, andersenFamilyResponse.RequestCharge);
        }
    
        // Create a family object for the Wakefield family
        Family wakefieldFamily = new Family
        {
            Id = "Wakefield.7",
            LastName = "Wakefield",
            Parents = new Parent[]
            {
                new Parent { FamilyName = "Wakefield", FirstName = "Robin" },
                new Parent { FamilyName = "Miller", FirstName = "Ben" }
            },
            Children = new Child[]
            {
                new Child
                {
                    FamilyName = "Merriam",
                    FirstName = "Jesse",
                    Gender = "female",
                    Grade = 8,
                    Pets = new Pet[]
                    {
                        new Pet { GivenName = "Goofy" },
                        new Pet { GivenName = "Shadow" }
                    }
                },
                new Child
                {
                    FamilyName = "Miller",
                    FirstName = "Lisa",
                    Gender = "female",
                    Grade = 1
                }
            },
            Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
            IsRegistered = true
        };
    
        try
        {
            // Read the item to see if it exists
            ItemResponse<Family> wakefieldFamilyResponse = await this.container.ReadItemAsync<Family>(wakefieldFamily.Id, new PartitionKey(wakefieldFamily.LastName));
            Console.WriteLine("Item in database with id: {0} already exists\n", wakefieldFamilyResponse.Resource.Id);
        }
        catch(CosmosException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            // Create an item in the container representing the Wakefield family. Note we provide the value of the partition key for this item, which is "Wakefield"
            ItemResponse<Family> wakefieldFamilyResponse = await this.container.CreateItemAsync<Family>(wakefieldFamily, new PartitionKey(wakefieldFamily.LastName));
    
            // Note that after creating the item, we can access the body of the item with the Resource property off the ItemResponse. We can also access the RequestCharge property to see the amount of RUs consumed on this request.
            Console.WriteLine("Created item in database with id: {0} Operation consumed {1} RUs.\n", wakefieldFamilyResponse.Resource.Id, wakefieldFamilyResponse.RequestCharge);
        }
    }
    
  4. Add a call to AddItemsToContainerAsync in the GetStartedDemoAsync method.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.AddItemsToContainerAsync();
    }
    

Select F5 to run your application.

Congratulations! You have successfully created two Azure Cosmos DB items.

Step 7: Query Azure Cosmos DB resources

Azure Cosmos DB supports rich queries against JSON documents stored in each collection. The following sample code shows how to run a query against the items we inserted in the previous step.

  1. Copy and paste the QueryItemsAsync method below your AddItemsToContainerAsync method.

    /// <summary>
    /// Run a query (using Azure Cosmos DB SQL syntax) against the container
    /// </summary>
    private async Task QueryItemsAsync()
    {
        var sqlQueryText = "SELECT * FROM c WHERE c.LastName = 'Andersen'";
    
        Console.WriteLine("Running query: {0}\n", sqlQueryText);
    
        QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
        FeedIterator<Family> queryResultSetIterator = this.container.GetItemQueryIterator<Family>(queryDefinition);
    
        List<Family> families = new List<Family>();
    
        while (queryResultSetIterator.HasMoreResults)
        {
            FeedResponse<Family> currentResultSet = await queryResultSetIterator.ReadNextAsync();
            foreach (Family family in currentResultSet)
            {
                families.Add(family);
                Console.WriteLine("\tRead {0}\n", family);
            }
        }
    }
    
  2. Add a call to QueryItemsAsync in the GetStartedDemoAsync method.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
        await this.AddItemsToContainerAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.QueryItemsAsync();
    }
    

Select F5 to run your application.

Congratulations! You have successfully queried against an Azure Cosmos DB container.

Step 8: Replace a JSON item

Now, we will update an item in Azure Cosmos DB.

  1. Copy and paste the ReplaceFamilyItemAsync method below your QueryItemsAsync method. Note we are changing the IsRegistered property of the Family and the Grade of one of the children.

    /// <summary>
    /// Replace an item in the container
    /// </summary>
    private async Task ReplaceFamilyItemAsync()
    {
        ItemResponse<Family> wakefieldFamilyResponse = await this.container.ReadItemAsync<Family>("Wakefield.7", new PartitionKey("Wakefield"));
        var itemBody = wakefieldFamilyResponse.Resource;
        
        // update registration status from false to true
        itemBody.IsRegistered = true;
        // update grade of child
        itemBody.Children[0].Grade = 6;
    
        // replace the item with the updated content
        wakefieldFamilyResponse = await this.container.ReplaceItemAsync<Family>(itemBody, itemBody.Id, new PartitionKey(itemBody.LastName));
        Console.WriteLine("Updated Family [{0},{1}].\n \tBody is now: {2}\n", itemBody.LastName, itemBody.Id, wakefieldFamilyResponse.Resource);
    }
    
  2. Add a call to ReplaceFamilyItemAsync in the GetStartedDemoAsync method.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
        await this.AddItemsToContainerAsync();
        await this.QueryItemsAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.ReplaceFamilyItemAsync();
    }
    

    Select F5 to run your application.

Congratulations! You have successfully replaced an Azure Cosmos DB item.

Step 9: Delete item

Now, we will delete an item in Azure Cosmos DB.

  1. Copy and paste the DeleteFamilyItemAsync method below your ReplaceFamilyItemAsync method.

    /// <summary>
    /// Delete an item in the container
    /// </summary>
    private async Task DeleteFamilyItemAsync()
    {
        var partitionKeyValue = "Wakefield";
        var familyId = "Wakefield.7";
    
        // Delete an item. Note we must provide the partition key value and id of the item to delete
        ItemResponse<Family> wakefieldFamilyResponse = await this.container.DeleteItemAsync<Family>(familyId,new PartitionKey(partitionKeyValue));
        Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, familyId);
    }
    
  2. Add a call to DeleteFamilyItemAsync in the GetStartedDemoAsync method.

    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
        await this.AddItemsToContainerAsync();
        await this.QueryItemsAsync();
        await this.ReplaceFamilyItemAsync();
    
        //ADD THIS PART TO YOUR CODE
        await this.DeleteFamilyItemAsync();
    }
    

Select F5 to run your application.

Congratulations! You have successfully deleted an Azure Cosmos DB item.

Step 10: Delete the database

Now we will delete our database. Deleting the created database will remove the database and all children resources (containers, items, and any stored procedures, user-defined functions, and triggers). We will also dispose of the CosmosClient instance.

  1. Copy and paste the DeleteDatabaseAndCleanupAsync method below your DeleteFamilyItemAsync method.

    /// <summary>
    /// Delete the database and dispose of the Cosmos Client instance
    /// </summary>
    private async Task DeleteDatabaseAndCleanupAsync()
    {
        DatabaseResponse databaseResourceResponse = await this.database.DeleteAsync();
        // Also valid: await this.cosmosClient.Databases["FamilyDatabase"].DeleteAsync();
    
        Console.WriteLine("Deleted Database: {0}\n", this.databaseId);
    
        //Dispose of CosmosClient
        this.cosmosClient.Dispose();
    }
    
  2. Add a call to DeleteDatabaseAndCleanupAsync in the GetStartedDemoAsync method.

    /// <summary>
    /// Entry point to call methods that operate on Azure Cosmos DB resources in this sample
    /// </summary>
    public async Task GetStartedDemoAsync()
    {
        // Create a new instance of the Cosmos Client
        this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
        await this.CreateDatabaseAsync();
        await this.CreateContainerAsync();
        await this.AddItemsToContainerAsync();
        await this.QueryItemsAsync();
        await this.ReplaceFamilyItemAsync();
        await this.DeleteFamilyItemAsync();
        await this.DeleteDatabaseAndCleanupAsync();
    }
    

Select F5 to run your application.

Congratulations! You have successfully deleted an Azure Cosmos DB database.

Step 11: Run your C# console application all together!

Select F5 in Visual Studio to build and run the application in debug mode.

You should see the output of your entire app in a console window. The output will show the results of the queries we added and should match the example text below.

Beginning operations...

Created Database: FamilyDatabase

Created Container: FamilyContainer

Created item in database with id: Andersen.1 Operation consumed 11.43 RUs.

Created item in database with id: Wakefield.7 Operation consumed 14.29 RUs.

Running query: SELECT * FROM c WHERE c.LastName = 'Andersen'

        Read {"id":"Andersen.1","LastName":"Andersen","Parents":[{"FamilyName":null,"FirstName":"Thomas"},{"FamilyName":null,"FirstName":"Mary Kay"}],"Children":[{"FamilyName":null,"FirstName":"Henriette Thaulow","Gender":"female","Grade":5,"Pets":[{"GivenName":"Fluffy"}]}],"Address":{"State":"WA","County":"King","City":"Seattle"},"IsRegistered":false}

Updated Family [Wakefield,Wakefield.7].
        Body is now: {"id":"Wakefield.7","LastName":"Wakefield","Parents":[{"FamilyName":"Wakefield","FirstName":"Robin"},{"FamilyName":"Miller","FirstName":"Ben"}],"Children":[{"FamilyName":"Merriam","FirstName":"Jesse","Gender":"female","Grade":6,"Pets":[{"GivenName":"Goofy"},{"GivenName":"Shadow"}]},{"FamilyName":"Miller","FirstName":"Lisa","Gender":"female","Grade":1,"Pets":null}],"Address":{"State":"NY","County":"Manhattan","City":"NY"},"IsRegistered":true}

Deleted Family [Wakefield,Wakefield.7]

Deleted Database: FamilyDatabase

End of demo, press any key to exit.

Congratulations! You've completed the tutorial and have a working C# console application!

Get the complete tutorial solution

If you didn't have time to complete the steps in this tutorial, or just want to download the code samples, you can get it from GitHub.

To build the GetStarted solution, you will need the following:

To restore the references to the Azure Cosmos DB .NET SDK in Visual Studio, right-click the GetStarted solution in Solution Explorer, and then click Restore NuGet Packages. Next, in the App.config file, update the EndPointUri and PrimaryKey values as described in Connect to an Azure Cosmos DB account.

That's it, build it, and you're on your way!

Next steps