在Cosmos DB中将具有动态属性的对象存储

内森·特雷格洛斯(Nathan Tregillus)

我有一个消息处理器,我想用一个已知模式的包装器来封装一堆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))'有一些无效的参数

我以为我可以将任何东西扔进这些文档中。我究竟做错了什么?我应该为这个Model属性使用动态以外的东西吗?

UPDATE我发现这与我如何对DocumentClient返回的任务调用Wait()方法有关。恢复到异步等待策略后,它便开始正常工作。

刘Liu

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

    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 });                     
    }

NotificationDetails类:

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; }
}

结果截图:

在此处输入图片说明

如果错误仍然存​​在,则最好与我们共享更详细的代码,以进行进一步的研究。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章