How to use Azure Cosmos DB in .Net

Take advantage of the Azure cloud’s fully managed, schema agnostic, NoSQL database-as-service for your .Net web applications

How to use Azure Cosmos DB in .NET
WikiImages (CC0)

Azure Cosmos DB is an easy-to-use, scalable, NoSQL database available in Microsoft’s Azure cloud. Cosmos DB is hosted on SSDs and hence data storage and retrieval is very fast. This database service also supports multiple data models including document, key-value, graph, and columnar, so can be leveraged for all kinds of applications. We will focus on Cosmos DB’s document data model, which is accessed through the SQL API (formerly known as the DocumentDB API).

Similar to MongoDB and RavenDB, the document data model in Azure Cosmos DB allows you to store data represented as JSON without an enforced schema. In this article I will discuss the use of Azure Cosmos DB as a JSON document store and how we can work with it in .Net.

Getting started with Azure Cosmos DB

First create a free Microsoft Azure account if you don’t have one. Next, create and configure an Azure Cosmos DB account from the Azure portal. When creating an Azure Cosmos DB account, you will be prompted to select any one of the five API options: Gremlin (graph database), MongoDB (document database), SQL (document database), Cassandra (columnar database), and Azure Table (key-value store). Select SQL as the API for your Azure Cosmos DB account. You can take a look at this Microsoft Quickstart to learn how to configure Azure Cosmos DB with the SQL API.

Now that you have your Cosmos DB account, create a new console application project in Visual Studio and save it with a name. Next, select the project in the Solution Explorer window and install the Microsoft.Azure.DocumentDB .Net client library in your project from the NuGet Package Manager window. Alternatively, you can install this library via the NuGet Package Manager console using the following command.

Install-Package Microsoft.Azure.DocumentDB

We will take advantage of this library to connect to Azure Cosmos DB using the SQL API.

Using the Microsoft.Azure.DocumentDB .Net SDK

To connect to Azure Cosmos DB and work with it using the .Net SDK, you should use the DocumentClient class. The following code snippet illustrates how you can create an instance of the DocumentClient class.

var client = new DocumentClient(new Uri(“https://writetheaccountnamehere.documents.azure.com:443/“), “specifythetokenhere”);

Note that the constructor of the DocumentClient class accepts the DocumentDB URI and the primary key as parameters. You can get these from the Azure portal.

Creating an Azure Cosmos DB database

The next thing you should do is create a database and a collection before you can store documents. A database is defined as a logical container of collections and documents. The following code snippet illustrates how you can create a new database.

var response = await client.CreateDatabaseAsync(new Database { Id ="Sample" });

Creating a document collection in Azure Cosmos DB

A collection is defined as a container of documents. To create a collection, you can use the following code. Note that in the code snippet below, “Sample” refers to the databaseId and “SampleCollection” refers to the document collection id respectively.

await client.CreateDocumentCollectionAsync(
      UriFactory.CreateDatabaseUri(“Sample”),
      new DocumentCollection { Id ="SampleCollection" });

Creating documents in Azure Cosmos DB

A document is represented as JSON and should have a unique ID property; if you haven’t specified the unique ID property, the runtime will generate a GUID when the document is created. Now consider the following class.

public class Author
    {
        [JsonProperty(PropertyName ="id")]
        public string Id { get; set; }
        [JsonProperty(PropertyName ="FirstName")]
        public string FirstName { get; set; }
        [JsonProperty(PropertyName ="LastName")]
        public string LastName { get; set; }
        [JsonProperty(PropertyName ="Address")]
        public string Address { get; set; }
    }

The following code snippet illustrates how you can create a document and store it inside a document collection.

await client.CreateDocumentAsync(
    UriFactory.CreateDocumentCollectionUri(“Sample”, “SampleCollection”),
    new Author
     {
       FirstName ="Joydip",
       LastName ="Kanjilal",
       Address ="Hyderabad"
     });

Here is the complete code listing that shows how you can create a new database, create a new collection inside that database, and create a document and store it inside the document collection.

string uri ="https://joydipkanjilal.documents.azure.com:443/";
string key ="Specify the key here";
var client = new DocumentClient(new Uri(uri), key);
var createDatabaseResponse = await client.CreateDatabaseAsync(new Database { Id ="Sample" });
var createDocumentCollectionResponse = await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(“Sample”), new DocumentCollection { Id ="SampleCollection" });
var response = await client.CreateDocumentAsync(
UriFactory.CreateDocumentCollectionUri(“Sample”, “SampleCollection”),
new Author
    {
        Id = “1”,
        FirstName ="Joydip",
        LastName ="Kanjilal",
        Address ="Hyderabad"
    });

Searching documents in Azure Cosmos DB

To read a single document, you can take advantage of the ReadDocumentAsync method and pass the document URI, collection ID, and document ID as parameters. Note that this method will throw an exception if the document is not available in the collection.

var response = await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(“Sample”, “SampleCollection”, “1”));
var author = JsonConvert.DeserializeObject<Author>(response.Resource.ToString());

To query documents you can take advantage of the CreateDocumentQuery method as shown in the code snippet below. This query will return a list of all authors who reside in Hyderabad.

IQueryable<Author> queryable =
client.CreateDocumentQuery<Author>(UriFactory.CreateDocumentCollectionUri
(“Sample”, “SampleCollection”)).Where(x => x.Address =="Hyderabad");
var authors = queryable.ToList();

Updating documents in Azure Cosmos DB

You can use the ReplaceDocumentAsync method to update a document in a collection asynchronously. The following code snippet shows how this can be done. Note that the ReplaceDocumentAsync method will throw an exception if the document does not exist.

await client.ReplaceDocumentAsync(
    UriFactory.CreateDocumentUri(“Sample”, “SampleCollection”, “1”),
    new Author
            {
                FirstName ="Joydip",
                LastName =  “Kanjilal”,
                Address =   “Hyderabad, INDIA”
            });

Alternatively you can use the UpsertDocumentAsync method to update a document. In this case, if the document doesn’t exist, a new document will be created in the collection.

await client.UpsertDocumentAsync(
    UriFactory.CreateDocumentCollectionUri(“Sample”, “SampleCollection”),
    new Author
            {
                FirstName ="Joydip",
                LastName =  “Kanjilal”,
                Address =   “Hyderabad, INDIA”
            });

Deleting documents in Azure Cosmos DB

The DeleteDocumentAsync method can be used to delete a document asynchronously. Here is a code snippet that illustrates this.

await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(“Sample”, “SampleCollection”, “1”));

A scalable, distributed, multi-model database service available in the Microsoft Azure cloud, Azure Cosmos DB presents almost unlimited possibilities for building applications. I will have more to say about using it as a document database in future posts here.

Copyright © 2018 IDG Communications, Inc.