Azure CosmosDB (Azure Cosmos DB – Globally Distributed Database Service (formerly DocumentDB) | Microsoft Azure) is a super set of the service once known as “Azure Document Db”. In short: “Azure CosmosDB ” = “Azure Document Db” + new data types + new APIs.
You can try CosmosDB for free on Azure or you can setup the CosmosDB on your local environment by following my previous blog. I am becoming a fan of .NET Core with all the features and it is getting better day by day . In this blog post i just wanted to take that initial steps of how to work with CosmosDB from .NET Core Client context. After reading this blog, you should be able to do the following with CosmosDB programmatically,
- Create Database
- Create Collection
- Create Documents
- Query a Document
- Delete Database
I have the following in my local environment , hope you guys have already have😊, if not start setting up.
- Windows 10 OS
- Azure CosmosDB Emulator
- Visual Studio Code editor with C# plugin
- .NET Core 2.0
Ok folks, lets get started.
As other tutorials, to make it simple I will be creating a dotnetcore console app to work with CosmosDB . With Net Core , we now have a CLI. Lets create the new app with the following steps. (I’ve mentioned in the previous blog)
- Open command prompt or poweshell (Administrator Mode)
- Navigate to your folder where you need to create the app
- Execute the following command
here -n denotes the name of the application, and -o tells the CLI to create a folder with that name and create the application inside the folder
Code.
Here is a screenshot of how it should look on your end:
I am using C# 7.1 feature to create a async Main method in my console app. For that, we will need to make a small change in our project file a little. Open CosmosDBClient.csproj file to edit. Add the following XML node to PropertyGroup node.
After changes, your csproj file should look like below:
Lets move to the core part of integrating CosmosDB with .netCore application and start building the features.
Step 2: Add CosmosDB Nuget Package
If you have followed the above steps, we have successfully created the application, next is to add reference to CosmosDB nuget package to get the client libraries. Advantage of these packages/libraries are, they make it easy to work with Cosmosdb.
- Open a command prompt and navigate to root of your project.
- Execute the following command
You might wonder the namespace has DocumentDB in it. In fact DocumetDB is where the whole journey started and hence the name sticks in Cosmos world too. If you now look at the project file a new reference for DocumentDB would have been added. Here is the screenshot of my project file.
Step 3: Creating Model for CosmosDB
Lets build the database. If you are new to CosmosDB you should know that CosmosDB has a query playground here https://www.documentdb.com/sql/demo. It is a sandboxed environment with couple of databases and you can try around with different queries you can write against the database. For this post, lets create the database named Course locally.
Since we our application is to deal with the Courses we need 4 Models here.
- Course
- Session
- Teacher
- Student
Here are the Models of the above 4.
Course.cs
Session.cs
Teacher.cs
Student.cs
Lets create the Client as the next step.
Step 4: Creating the Client
Next step you will need to instantiate the CosmosDb client before we do anything with the database. In order to connect to the local instance of the cosmosDb, we need to configure 2 things,
- URL of the CosmosDb instane
- Authentication key needed to authenticate.
When the method Run is exectued the Client is instantiated with the local CosmosDB emulator.
Step 5: Lets start building the features
Next step is to build the features as listed above. Lets add the methods inside the Async method.
Creating Database:
To create a new database programmatically, we make use of CreateDatabaseAsync() or CreateDatabaseIfNotExistsAsync(). When creating the database we pass the database name. Here is the code snippet:
When you refresh the URL of local CosmosDB emulator, You should see the database created in your local db emulator as follows,
Creating Collection:
Once the database is created, we can then create a collection. We make use of CreateDocumentCollectionAsync() or CreateDocumentCollectionIfNotExistsAsync().
We will need to provide what is known as the database link (basically the URI at which the db can be reached) and the collection name to the create method. Here is the code snippet:
Now you should the the Collection for Course is created as follows,
Creating Document :
After creating the database and collection, we can now create the documents. We make use of CreateDocumentAsync() for this purpose. We will need to pass the URI of the collection under which we want to create the document and the document data itself. In this example we make use of the Course data mode i showed earlier and pass it to the create method. Here is the code snippet:
You should see the document inserted in localdb Emulator as follows.
Querying Document:
Now that we have created a document, we can see how to query it. We can make use of CreateDocumentQuery() method for this purpose. We will need to pass the collection link on which we need to query. We can then build the query as a LINQ expression and the client library does the rest. This is the best part of the client library. It has the ability to translate your LINQ expression to cosmos REST URIs without me having to crack my head in constructing those URIs. Here is the code snippet:
Note that you will need to import System.Linq for the LINQ expression to work.
Deleting Database:
Finally, we can make use of DeleteDatabaseAsync() method to delete the database programmatically. We will need to provide the database link to the delete method. We can use the UriFactory.CreateDatabaseUri() helper method to create the database link. Here is the code snippet:
Well, those are the main features that Azure CosmosDB client provides and if you are stuck with any of the steps above , you can check out the repository i have added with the samples.
Happy Coding! Lets spread Azure's CosmosDB to the world.