Converting created document result to POCO

(Copying over Andrew Davis's answer, from the DocumentDB MSDN forums, for the stackoverflow community)

The simplest way would be to have your Employee class inherit from Document, and then cast result.Resource to Employee. If you don't want to inherit from Document, you could also define an explicit cast between Document and Employee.

Having the Employee class inherit from Document should work out-of-the-box if the names of the members of your Employee class match the names of the corresponding properties of the JSON representation.

Defining your own type conversion gives you more control, and might look something like this:

public static explicit operator Employee(Document doc)
{
    Employee emp = new Employee();
    emp.Name = doc.GetPropertyValue<string>("employeeName");
    emp.Number = doc.GetPropertyValue<int>("employeeNumber");
    /* and so on, for all the properties of Employee */
    return emp;
}

This would define an explicit cast from Document to Employee. You'll have to make sure the GetPropertyValue strings (and type arguments) match your JSON properties.


I wrote an extension method to do this:

public static async Task<T> ReadAsAsync<T>(this Document d)
{
    using (var ms = new MemoryStream())
    using (var reader = new StreamReader(ms))
    {
        d.SaveTo(ms);
        ms.Position = 0;
        return JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
    }
}

Then you can use it like

Document d;
var myObj = await d.ReadAsAsync<MyObject>();

You can do a dynamic cast like this:

Employee emp = (dynamic)result.Resource;