Share via


DocumentDB Add and Read – Simple Approach

I wanted to create a simple sample which would Add and Read records in DocumentDB.

Created one Windows Forms Application, added NuGet Package

image

Then in the Windows Forms I have added simple Text box to enter data and grid to display it.

image

The data model would look like, this has dependency

 using Newtonsoft.Json;

 

 //Employee Data Model
public class Employee
{
    [JsonProperty(PropertyName = "id")]
    public string id { get; set; }
    [JsonProperty(PropertyName = "FullName")]
    public string FullName { get; set; }
}

After that behind the button’s click event, with dependencies

 using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;

using Microsoft.Azure.Documents.Linq; 

The actual working code,

 //Intializing the connection using the Uri and Key
var client = new DocumentClient(new Uri("https://gids.documents.azure.com:443/"), 
    "eBuaGTYZJ+zjyCxbIWNbT5mGgI75Uo42su6PMbK1W6zT0CbaxqfBIXIM/UlZ6AXaBsUscNZN0fFTeDJaxAsSzg==");
//Give a name to a database and create if it does not exist

string databaseId = "hrdatabase";

var db = client.CreateDatabaseQuery()
            .Where(d => d.Id == databaseId)
            .AsEnumerable()
            .FirstOrDefault();
if (db == null)
{
    db = client.CreateDatabaseAsync(new Database { Id = databaseId }).Result;
}
//Get a Collection and create if does  not exists

string collectionId = "employee_test";

var col = client.CreateDocumentCollectionQuery(db.SelfLink)
                .Where(c => c.Id == collectionId)
                .AsEnumerable()
                .FirstOrDefault();
if (col == null)
{
    var collectionSpec = new DocumentCollection { Id = collectionId };
    var requestOptions = new RequestOptions { OfferType = "S1" };
    col = client.CreateDocumentCollectionAsync(db.SelfLink, collectionSpec, requestOptions).Result;
}
//There is a input text box, then insert the data (any format)

if (txtFullName.Text.Trim() != "") { 
    //Insert Record
    Employee emp = new Employee() { FullName = txtFullName.Text };
    client.CreateDocumentAsync(col.SelfLink, emp);
            
    MessageBox.Show("Records Added");
    txtFullName.Text = "";
}
//Display

var dataList = client.CreateDocumentQuery<Employee>(col.DocumentsLink).AsEnumerable();

dataGridEmployee.DataSource = dataList.ToList();

This works pretty well. I wanted to just let you know how simple it is. I did not follow any pattern. You can only become Formula One driver if you know the driving. Back to basic.

Namoskar!!!