c# - 为什么 CosmosDB 只保存公共(public)成员?

标签 c# azure-cosmosdb

我有一个包含一些 protected 和私有(private)成员的测试类:

    public class Doc_PrivateValues : Document
    {
        public int PublicIntProperty { get; set; }
        public int PublicIntField;

        protected int ProtectedIntProperty { get; set; }
        protected int ProtectedIntField;

        private int PrivateIntProperty { get; set; }
        private int PrivateIntField;

        public SimpleDocument PublicDocument;
        protected SimpleDocument ProtectedDocument;
        private SimpleDocument PrivateDocument;

        public SimpleStruct PublicStruct;
        protected SimpleStruct ProtectedStruct;
        private SimpleStruct PrivateStruct;
    }

我以非常简单的方式将此文档保存到 CosmosDB 中:

        Microsoft.Azure.Documents.Document result = CosmosClient.CreateDocumentAsync( CosmosCollection.SelfLink, document ).Result.Resource;
        document.id = result.Id;

数据库中的结果:

{
    "PublicIntField": 2,
    "PublicDocument": {
        "StrVal": "seven",
        "IntVal": 7,
        "id": null
    },
    "PublicStruct": {
        "StrVal": "ten",
        "IntVal": 10
    },
    "PublicIntProperty": 1,
    "id": "58f18ccf-9e0c-41a6-85cd-a601f12a120a",
    "_rid": "mPlfANiOud4BAAAAAAAAAA==",
    "_self": "dbs/mPlfAA==/colls/mPlfANiOud4=/docs/mPlfANiOud4BAAAAAAAAAA==/",
    "_etag": "\"00000000-0000-0000-8b2a-d853688c01d4\"",
    "_attachments": "attachments/",
    "_ts": 1543856923
}

文档仅包含公共(public)成员。 我怎样才能同时保存非公共(public)成员?

谢谢!

最佳答案

JSON.NET 无法访问非公共(public)属性,这就是它无法处理它们的原因。它根本看不到它们。

您可以编写自己的 ContractResolver,它使用反射来获取非公共(public)属性。

然后您可以简单地在 DocumentClient 或操作级别上提供 JsonSerializerSettings

这里描述了这样做的方法:JSON.Net: Force serialization of all private fields and all fields in sub-classes

关于c# - 为什么 CosmosDB 只保存公共(public)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598632/

相关文章:

c# - 如何删除所有出现的字符/子字符串?

c# - MessageBox 自动继续,无需按下按钮

azure - 从本地计算机连接到 Azure Cosmos DB 时出现 "Service is currently unavailable"

azure - DocumentDB 吞吐量从 1000 缩减至 400

javascript - 在 Cosmos DB 存储过程中创建和比较日期

c# - 在我的 CLR 项目中添加包含使得 WLR 无法在启用/clr 的情况下进行编译

c# - WPF TextBox 不允许有空格

c# - LINQ 删除组中具有特定值的项目

java - 查询表达式中指示的分区键与 cosmos db 中的 feedoptions 中指示的分区键之间的差异

azure - 可以使用 CosmosDB (DocumentDB) Xamarin 和 dot .net 标准库。