将创建的文档结果转换为POCO [英] Converting created document result to POCO

查看:67
本文介绍了将创建的文档结果转换为POCO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code that calls DocumentDB and creates a new Employee document. How do I then convert the result to Employee document again? Basically, I want to capture the created document and convert it to 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?
}

推荐答案

(从 DocumentDB MSDN论坛复制安德鲁·戴维斯的答案,用于stackoverflow社区)

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

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

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.

如果Employee类的成员名称与JSON表示形式的相应属性的名称匹配,那么让Employee类从Document继承就可以直接使用.

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;
}

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

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.

这篇关于将创建的文档结果转换为POCO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆