将创建的文档结果转换为POCO

Sam*_*Sam 18 azure-cosmosdb

我有以下代码调用DocumentDB并创建一个新的Employee文档.如何再将结果转换为Employee文档?基本上,我想捕获创建的文档并将其转换为Employee对象.

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?
}
Run Code Online (Sandbox Code Playgroud)

Arn*_*rty 46

你可以做这样的动态演员:

Employee emp = (dynamic)result.Resource;


mdi*_*kin 8

我写了一个扩展方法来做到这一点:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像

Document d;
var myObj = await d.ReadAsAsync<MyObject>();
Run Code Online (Sandbox Code Playgroud)


And*_*Liu 7

(从DocumentDB MSDN论坛上复制Andrew Davis的回答,用于stackoverflow社区)

最简单的方法是让您的Employee类继承Document,然后将result.Resource转换为Employee.如果您不想从Document继承,您还可以在Document和Employee之间定义显式转换.

如果Employee类的成员名称与JSON表示的相应属性的名称匹配,那么从Document继承Employee类应该是开箱即用的.

定义自己的类型转换可以让您获得更多控制权,并且可能看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

这将定义从Document到Employee的显式转换.您必须确保GetPropertyValue字符串(和类型参数)与您的JSON属性匹配.