The goal of this post is to write a C# sample application to perform basic requests to Azure DocumentDB: Create, Read, Update, Delete and Find documents.
You can find the code on my github: https://github.com/softwarejc/documentdb
Relational databases have been the dominant approach to store data for decades and they will probably be used for a very long time. However a lot of modern applications work with JSON, a format that does not fit naturally in a relational system.
NoSQL databases came to solve this problem and to improve the scalability of relational databases. NoSQL also allows working with data that change fast without having to change the database.
There are different types of NoSQL databases:
- Document stores: MongoDB, Azure DocumentDB
- Key/Value stores: Riak
- Column stores: Cassandra
- Big data analytics: HDInsight, Hadoop
The focus of this post is the document store offered by Microsoft: Azure DocumentDB.
You can read more about MongoDB vs DocumentDB here: http://justazure.com/mongodb-vs-azure-documentdb/
Create a DocumentDB in Azure
The creation of a DocumentDB is very straight forward.
Scott Hanselman explains it very good in this video:
You can read the about pricing information here:
How to use DocumentDB with C#
DocumentDB officially supports the following programming languages:
We will be using .NET C# 6.
The first thing that we have to do is to add a Nuget package that will do part of the job for us: Microsoft.Azure.DocumentDB:
The class DocumentClient included in the nuget provides a client-side logical representation of the Azure DocumentDB service. This client is used to configure and execute requests against the service.
DocumentClient class MSDN documentation:
To create an instance of the class you need your database URL and access key:
That’s all, you can use some of the following methods to access your database:
- CreateDatabaseAsync: Create a database.
- CreateDocumentCollectionAsync: Create a document collection (~table).
- CreateDocumentAsync: Create a document.
- ReplaceDocumentAsync: Update a document.
- DeleteDocumentAsync: Delete a document.
- CreateDocumentQuery: Find documents.
I am used to access the database using Entity Framework I would like to also use a NoSQL database like DocumentDB in the same way, something like:
This is possible writing a couple of classes:
My NoSQL context:
A generic class to deal with containers:
See the implementation of that class using C# 6.0 on my github:
DocumentDB is a great solution to use a NoSQL storage. If you are a .NET developer you will fell yourself at home using it.