Tutorial: 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 or later of the Azure Cosmos DB .NET SDK. You can work with .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
  • Performing create, read, update, and delete (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, skip this section. To use the Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to set up the emulator. Then skip ahead to Step 2: Set up your Visual Studio project.

  1. Go to the Azure portal to create an Azure Cosmos DB account. Search for and select Azure Cosmos DB.

    The Azure portal Databases pane

  2. Select Add.

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

    Setting Value Description
    Subscription Subscription name Select the Azure subscription that you want to use for this Azure Cosmos account.
    Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group.
    Account Name A unique name Enter a name to identify your Azure Cosmos 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. It must be between 3-31 characters in length.
    API The type of account to create Select Core (SQL) to create a document database and query by using SQL syntax.

    The API determines the type of account to create. Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. Currently, you must create a separate account for each API.

    Learn more about the SQL API.
    Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data.

    The new account page for Azure Cosmos DB

  4. Select Review + create. You can skip the Network and Tags sections.

  5. Review the account settings, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete.

    The Azure portal Notifications pane

  6. Select Go to resource to go to the Azure Cosmos DB account page.

    The Azure Cosmos DB account page

Step 2: Set up your Visual Studio project

  1. Open Visual Studio and select Create a new project.

  2. In Create a new project, choose Console App (.NET Framework) for C#, then select Next.

  3. Name your project CosmosGettingStartedTutorial, and then select Create.

    Configure your project

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

  5. In the NuGet Package Manager, select Browse and search for Microsoft.Azure.Cosmos. Choose Microsoft.Azure.Cosmos and select Install.

    Install NuGet for Azure Cosmos DB Client SDK

    The package ID for the Azure Cosmos DB SQL API Client Library is Microsoft Azure Cosmos DB Client Library.

Great! Now that we finished the setup, let's start writing some code. For the completed project of this tutorial, see Developing a .NET console app using Azure Cosmos DB.

Step 3: Connect to an Azure Cosmos DB account

  1. 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. Add these constants and variables into your Program class.

    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're familiar with the previous version of the .NET SDK, you may be familiar with 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. For more information, see Work with databases, containers, and items in Azure Cosmos DB.

  3. Open the Azure portal. Find your Azure Cosmos DB account, and then select Keys.

    Get Azure Cosmos DB keys from Azure portal

  4. In Program.cs, replace <your endpoint URL> with the value of URI. Replace <your primary key> with the value of PRIMARY KEY.

  5. Below the Main method, add a new asynchronous task called GetStartedDemoAsync, which instantiates our new CosmosClient.

    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);
    }
    

    We use GetStartedDemoAsync as the entry point that calls methods that operate on Azure Cosmos DB resources.

  6. Add the following code to run the GetStartedDemoAsync asynchronous task from your Main method. The Main method catches exceptions and writes 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();
        }
    }
    
  7. Select F5 to run your application.

    The console displays the message: End of demo, press any key to exit. This message confirms that your application made a connection to Azure Cosmos DB. You can then close the console window.

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

Step 4: Create a database

A database is the logical container of items partitioned across containers. Either the CreateDatabaseIfNotExistsAsync or CreateDatabaseAsync method of the CosmosClient class can create a database.

  1. Copy and paste the CreateDatabaseAsync method below your GetStartedDemoAsync method.

    /// <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);
    }
    

    CreateDatabaseAsync creates a new database with ID FamilyDatabase if it doesn't already exist, that has the ID specified from the databaseId field.

  2. Copy and paste the code below where you instantiate 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();
    }
    

    Your Program.cs 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 CosmosGettingStartedTutorial
    {
        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);
            }
        }
    }
    
  3. Select F5 to run your application.

    Note

    If you get a "503 service unavailable exception" error, it's possible that the required ports for direct connectivity mode are blocked by a firewall. To fix this issue, either open the required ports or use the gateway mode connectivity as shown in the following code:

      // Create a new instance of the Cosmos Client in Gateway mode
      this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, new CosmosClientOptions()
             {
                 ConnectionMode = ConnectionMode.Gateway
             });
    

Congratulations! You've successfully created an Azure Cosmos database.

Step 5: Create a container

Warning

The method CreateContainerIfNotExistsAsync creates 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 method 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 creates a new container with the ID FamilyContainer if it doesn't already exist, by using 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();
    }
    
  3. Select F5 to run your application.

Congratulations! You've successfully created an Azure Cosmos container.

Step 6: Add items to the container

The CreateItemAsync method of the CosmosContainer class can create an item. 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 container.

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

  1. Select Ctrl+Shift+A to open Add New Item. 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. Back in Program.cs, add the AddItemsToContainerAsync method after your CreateContainerAsync method.

    /// <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.  
            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);
        }
    }
    

    The code checks to make sure an item with the same ID doesn't already exist. We'll insert two items, one each for the Andersen Family and the Wakefield Family.

  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();
    }
    
  5. Select F5 to run your application.

Congratulations! You've successfully created two Azure Cosmos items.

Step 7: Query Azure Cosmos DB resources

Azure Cosmos DB supports rich queries against JSON documents stored in each container. For more information, see Getting started with SQL queries. 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 after 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();
    }
    
  3. Select F5 to run your application.

Congratulations! You've successfully queried an Azure Cosmos container.

Step 8: Replace a JSON item

Now, we'll update an item in Azure Cosmos DB. We'll change the IsRegistered property of the Family and the Grade of one of the children.

  1. Copy and paste the ReplaceFamilyItemAsync method after your QueryItemsAsync method.

    /// <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();
    }
    
  3. Select F5 to run your application.

Congratulations! You've successfully replaced an Azure Cosmos item.

Step 9: Delete item

Now, we'll delete an item in Azure Cosmos DB.

  1. Copy and paste the DeleteFamilyItemAsync method after 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();
    }
    
  3. Select F5 to run your application.

Congratulations! You've successfully deleted an Azure Cosmos item.

Step 10: Delete the database

Now we'll delete our database. Deleting the created database removes the database and all children resources. The resources include containers, items, and any stored procedures, user-defined functions, and triggers. We also dispose of the CosmosClient instance.

  1. Copy and paste the DeleteDatabaseAndCleanupAsync method after 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();
    }
    
  3. Select F5 to run your application.

Congratulations! You've successfully deleted an Azure Cosmos 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 shows the results of the queries we added. It 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 download it.

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

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

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

Next steps