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

Bri*_*Rak 17 c# json azure azure-cosmosdb

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

public class Person
{
    public string Name;
    public int Age;
}
Run Code Online (Sandbox Code Playgroud)

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

var person = new Person { ... };
client.CreateDocumentAsync(myCollectionLink, person);
Run Code Online (Sandbox Code Playgroud)

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

public class Person: Microsoft.Azure.Documents.Document
{
    public string Name;
    public int Age;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

    [JsonProperty(PropertyName="age")]
    public int Age;
}
Run Code Online (Sandbox Code Playgroud)

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

我的问题是...... 为什么会这样?我是从文件衍生出来做错了吗?非常感谢您的反馈意见.

Rya*_*our 24

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

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

public class Person: Microsoft.Azure.Documents.Resource
{
    public string Name;
    public int Age;
}
Run Code Online (Sandbox Code Playgroud)

  • 完全救了我.在我的生活中,我找不到这样的任何文档.谢谢 (4认同)
  • 是否有任何关于使用从资源继承的普通POCO或使用动态对象和/或优点等的文档? (2认同)
  • 我们在DocDb中使用POCO的时间最长,并且想开始利用_ts和_etag,因此我们扩展了Document(可能来自示例或SO答案)。由于文档的动态性质,我们看到了一些非常讨厌的行为(例如,序列化JSON中的重复键)。以下是一些文档,说扩展资源不是一个坏主意:https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.azure.documents.client.documentclient.createdocumentasync?view=azure-dotnet (2认同)