# Automating Database and Container Creation in Cosmos DB

In this short post we would look into how to automate the creation of an Azure Cosmos database and container through an C# console application.

In the [previous post](https://www.azureguru.net/getting-started-with-cosmos-db-on-azure) we saw how easy and quick it is to create a Cosmos DB instance in no time.

### **Lets Start**

Log into Azure portal and search for Cosmos DB instance. In the previous article we named the instance as "**mycosmos-database"**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724364107980/084031b8-8058-47c8-b8b0-b2e66676e83f.png align="center")

Navigate to the home page of the Cosmos DB instance and click Data Explorer.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724364418205/04975771-40aa-4fc2-b1b4-640222811725.png align="center")

There aren't any databases or containers on the instance. The key configs required to set up the database and container is the `URI` and the `Primary Key`. You can find them after clicking the `Keys` option of the cosmos instance.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724364566382/31a9d6ac-9683-4c7a-b4c9-4ac55dd8c832.png align="center")

Create a new console application in Visual Studio and add the following NuGet package to the project.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724364954524/a058fca6-5e71-43f6-946e-12b44c729f7e.png align="center")

Add the above reference to the console application.

```csharp
using Microsoft.Azure.Cosmos;
```

We will have to set values for `COSMOS_ENDPOINT` and `COSMOS_KEY` keywords. The values are available under the `URI` and `PRIMARY KEY` section that I marked in the earlier screenshot.

In the Console application add the following procedure to set the values for `COSMOS_ENDPOINT` and `COSMOS_KEY` that are set as environmental variables.

```csharp
 public static void Set_Env_Variables(string name, string value)
 {
     Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Process);
 }
```

Now add two static variables at the class level

```csharp
 static CosmosClient cosmosclient;
 static Container container;
```

Create a method named `Create_Database_Container` .This method will create the new database and the container.

In the method, the name for the database is set to `Product` and the container name is `ProductContainer` which is partitioned on `ProductRegion`**.**

```csharp
 public static async Task<Microsoft.Azure.Cosmos.Container> Create_Database_Container()
 {

     cosmosclient = new(
     accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT"),
     authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")
     );

     Database database = await cosmosclient.CreateDatabaseIfNotExistsAsync(id: "Product");
     container = await database.CreateContainerIfNotExistsAsync(id: "ProductContainer", partitionKeyPath: "/ProductRegion", throughput: 400);
     return container;

 }
```

The method basically would check if there is an pre existing database and container with the same names and if not then it creates them.

I have hard coded the database and container names in the method. To make them dynamic their values can be set in the JSON configuration of the application and read from there.

In the `Main` method of the project add the following code:

```csharp
public static void Main(string[] args)
{

    Set_Env_Variables("COSMOS_ENDPOINT", "Your Cosmos DB URI");
    Set_Env_Variables("COSMOS_KEY", "Your Cosmos DB Primary Key");

    Create_Database_Container().GetAwaiter().GetResult();

    if (container == null)
    {
        Console.WriteLine("Container creation failed");
    }
    else
    {
        Console.WriteLine("Container created successfully");
    }

}
```

The `Main` method which is the entry point for the application calls the `Create_Database_Container()` method and to validate the success it checks the value of the static variable `container`**.** If its value isn't null then it indicates the creation of the container and database is successful.

Checking on the Azure portal we should have a database called `Product` with a newly created container called `Product_Container`**.**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1724367325263/6e2a37ef-6192-4661-8148-97e2a1cebd1e.png align="center")

Here is the complete code :

```csharp
using Microsoft.Azure.Cosmos;
using PartitionKey = Microsoft.Azure.Cosmos.PartitionKey;

namespace CosmosDB
{
    public class Program
    {
        static CosmosClient cosmosclient;
        static Container container;

        public static void Main(string[] args)
        {

            Set_Env_Variables("COSMOS_ENDPOINT", "Your Cosmos DB URI");
            Set_Env_Variables("COSMOS_KEY", "Your Cosmos DB Primary Key");

             Create_Database_Container().GetAwaiter().GetResult();

            if (container == null)
            {
                Console.WriteLine("Container creation failed");
            }
            else
            {
                Console.WriteLine("Container created successfully");

            }

        }

        public static async Task<Microsoft.Azure.Cosmos.Container> Create_Database_Container()
        {

            cosmosclient = new(
            accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT"),
            authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")
            );

            Database database = await cosmosclient.CreateDatabaseIfNotExistsAsync(id: "Product");
            container = await database.CreateContainerIfNotExistsAsync(id: "ProductContainer", partitionKeyPath: "/ProductRegion", throughput: 400);

            return container;

        }

        public static void Set_Env_Variables(string name, string value)
        {
            Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Process);
        }
    }

}
```

In the [next post](https://www.azureguru.net/crud-operations-in-cosmos-db) we would see how to perform data operations on the database and the container that we created in this article.

Thanks for reading !!!
