首页 文章

我的Azure DocumentDB文档类是否应继承自Microsoft.Azure.Documents.Document?

提问于
浏览
16

我看到一些奇怪的行为保存到DocumentDB . 我开始使用看起来像这样的普通旧类来保存文档:

public class Person
{
    public string Name;
    public int Age;
}

我保存这些文件是这样的:

var person = new Person { ... };
client.CreateDocumentAsync(myCollectionLink, person);

这很好 . 保存的属性与类中的名称完全相同 . 然后我意识到我需要文档的SelfLink才能执行更新和删除 . “啊,”我想 . “我只是从Document中衍生出来,就像这样:

public class Person: Microsoft.Azure.Documents.Document
{
    public string Name;
    public int Age;
}

然而,令我惊讶的是,当我进行此更改时,除了DocumentDB本身分配的“id”属性外,新文档创建完全空白 .

我多次仔细检查 . 从文档派生可防止保存文档中的自定义属性...

...除非我用[JsonProperty]明确地装饰每一个,如下所示:

public class Person: Document
{
    [JsonProperty(PropertyName="name")]
    public string Name;

    [JsonProperty(PropertyName="age")]
    public int Age;
}

然后它再次工作(当然,使用新的更多JSON适当的camelCase属性名称) . 并且,在检索时,对象将填充我需要更新和删除的SelfLink属性 . 都好 .

我的问题是... Why did this happen? Am I doing something wrong by deriving from Document? 您的反馈将非常感激 .

1 回答

  • 23

    此行为归因于JSON.NET如何处理动态对象的属性 . 除非用JsonProperty属性修饰它们,否则它会有效地忽略它们 .

    您可以使用普通POCO,也可以从Resource(如下所示)扩展,这是Document本身扩展的静态对象 .

    public class Person: Microsoft.Azure.Documents.Resource
    {
        public string Name;
        public int Age;
    }
    

相关问题