我的 Azure DocumentDB 文档 类 应该继承自 Microsoft.Azure.Documents.Document 吗?
Should my Azure DocumentDB document classes inherit from Microsoft.Azure.Documents.Document?
我在保存到 DocumentDB 时发现了一些奇怪的行为。我开始使用看起来像这样的普通旧 class 保存文档:
public class Person
{
public string Name;
public int Age;
}
我这样保存这些文档:
var person = new Person { ... };
client.CreateDocumentAsync(myCollectionLink, person);
这很好用。属性以 class 中的名称保存。然后我意识到我需要文档的 SelfLink 才能执行更新和删除。 "Ah,"我想。 “我将直接从 Document 派生,像这样:
public class Person: Microsoft.Azure.Documents.Document
{
public string Name;
public int Age;
}
然而,令我惊讶的是,当我进行此更改时,新文档创建时完全空白,除了由 DocumentDB 本身分配的 "id" 属性。
我仔细检查了多次。从 Document 派生会阻止我在文档中的自定义属性被保存...
...除非我用 [JsonProperty] 明确地装饰每个,就像这样:
public class Person: Document
{
[JsonProperty(PropertyName="name")]
public string Name;
[JsonProperty(PropertyName="age")]
public int Age;
}
然后它再次工作(当然,使用新的更 JSON-适当的驼峰式 属性 名称)。而且,在检索时,对象会填充我更新和删除所需的 SelfLink 属性。一切顺利。
我的问题是...为什么会这样?我从 Document 派生是不是做错了什么?非常感谢您的反馈。
此行为归因于 JSON.NET 如何处理动态对象的属性。
它会有效地忽略它们,除非您使用 JsonProperty 属性修饰它们。
您可以使用普通 POCO,也可以从 Resource(如下所示)扩展,它是 Document 本身扩展的静态对象。
public class Person: Microsoft.Azure.Documents.Resource
{
public string Name;
public int Age;
}
我在保存到 DocumentDB 时发现了一些奇怪的行为。我开始使用看起来像这样的普通旧 class 保存文档:
public class Person
{
public string Name;
public int Age;
}
我这样保存这些文档:
var person = new Person { ... };
client.CreateDocumentAsync(myCollectionLink, person);
这很好用。属性以 class 中的名称保存。然后我意识到我需要文档的 SelfLink 才能执行更新和删除。 "Ah,"我想。 “我将直接从 Document 派生,像这样:
public class Person: Microsoft.Azure.Documents.Document
{
public string Name;
public int Age;
}
然而,令我惊讶的是,当我进行此更改时,新文档创建时完全空白,除了由 DocumentDB 本身分配的 "id" 属性。
我仔细检查了多次。从 Document 派生会阻止我在文档中的自定义属性被保存...
...除非我用 [JsonProperty] 明确地装饰每个,就像这样:
public class Person: Document
{
[JsonProperty(PropertyName="name")]
public string Name;
[JsonProperty(PropertyName="age")]
public int Age;
}
然后它再次工作(当然,使用新的更 JSON-适当的驼峰式 属性 名称)。而且,在检索时,对象会填充我更新和删除所需的 SelfLink 属性。一切顺利。
我的问题是...为什么会这样?我从 Document 派生是不是做错了什么?非常感谢您的反馈。
此行为归因于 JSON.NET 如何处理动态对象的属性。 它会有效地忽略它们,除非您使用 JsonProperty 属性修饰它们。
您可以使用普通 POCO,也可以从 Resource(如下所示)扩展,它是 Document 本身扩展的静态对象。
public class Person: Microsoft.Azure.Documents.Resource
{
public string Name;
public int Age;
}