代码之家  ›  专栏  ›  技术社区  ›  Nathan Tregillus

在cosmos数据库中存储具有动态特性的对象

  •  3
  • Nathan Tregillus  · 技术社区  · 7 年前

    我有一个消息处理器,我想用一个json块和一个已知模式的包装器,但是属性是一个动态对象,如下所示:

    public class NotificationDetails
    {
        [JsonProperty(PropertyName = "id")]
        public string NotificationID { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateSent { get; set; }
        public string TemplateUrl { get; set; }
        public dynamic Model { get; set; }
    }
    

    如您所见,最后一个属性是动态的。通知都有不同的模型模式,所以我希望它只是作为嵌套对象存储。

    也就是说,当我试图通过

    client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId), item)
    

    我收到以下错误消息:

    “MyClass.CreateNotification(NotificationDetails))的最佳重载方法匹配项具有一些无效参数

    我想我可以把任何东西都扔进这些文件里。我做错什么了?我应该为这个模型属性使用动态以外的其他东西吗?

    更新 我发现这与我如何对从documentclient返回的任务调用wait()方法有关。一旦我恢复到异步等待策略,它就开始正常工作了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Lee Liu    7 年前

    根据你的描述。我已经测试了你的代码,它的工作原理如下。你可以参考我所做的:

        public static void CreateCosmosDocument()
        {
            DocumentClient client = new DocumentClient(new Uri("https://xxxxx/"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJxxxxM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==", new ConnectionPolicy { EnableEndpointDiscovery = false });
    
            TestEntity testEntity = new TestEntity { x = 11, y = 11, name = "wakaka", dynam = "hello dynam" };
            var createdItem = client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("ToDoList", "Items"), new NotificationDetails { DateCreated=DateTime.Now, DateSent=DateTime.Now, TemplateUrl="www.baidu.com", Model= testEntity });                     
        }
    

    通知类别详细信息:

    public class NotificationDetails
    {
        [JsonProperty(PropertyName = "id")]
        public string NotificationID { get; set; }
        public DateTime? DateCreated { get; set; }
        public DateTime? DateSent { get; set; }
        public string TemplateUrl { get; set; }
        public dynamic Model { get; set; }
    }
    

    充当嵌套对象的TestEntity类:

    class TestEntity
    {
    
        public ObjectId _id { get; set; }
    
        public string name { get; set; }
    
        public double x { get; set; }
    
        public double y { get; set; }
    
        public double z { get; set; }
    
        public dynamic dynam { get; set; }
    }
    

    结果截图:

    enter image description here

    如果错误仍然发生,您最好与我们共享更详细的代码,以便进一步研究。

    推荐文章