Convert generated document to POCO

I have the following code that calls DocumentDB and creates a new Employee document. How do I convert the result to an Employee document again? Basically, I want to capture the created document and convert it to an Employee object.

var result = await client.CreateDocumentAsync(collection.SelfLink, employee); if(result.StatusCode == System.Net.HttpStatusCode.Created) { Employee emp = result.Resource; // How do I convert the result to Employee object here? } 
+8
azure-cosmosdb
source share
3 answers

(Copy Andrew Davis answer from MSDN Forums for DocumentDB for stackoverflow community)

The simplest way would be to inherit the Employee class from Document, and then pour result.Resource for Employee. If you do not want to inherit from the document, you can also define explicit casting between the document and the employee.

Having the Employee class inherited from Document should work if the member names of your Employee class match the names of the corresponding JSON view properties.

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 will need to make sure that the GetPropertyValue strings (and type arguments) match your JSON properties.

+5
source share

You can do a dynamic action as follows:

Employee emp = (dynamic)result.Resource;

+22
source share

I wrote an extension method for 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 as

 Document d; var myObj = await d.ReadAsAsync<MyObject>(); 
+1
source share

All Articles