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

Nat*_*lus 5 .net c# azure-cosmosdb

我有一个消息处理器,我想在其中获取一堆带有已知模式包装器的 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; }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,最后一个属性是动态的。通知都将具有不同的模型模式,因此我希望将其存储为嵌套对象。

也就是说,当我尝试通过创建对象时

client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, collectionId), item)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

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

我以为我可以在这些文档中添加任何内容。我究竟做错了什么?对于这个模型属性,我应该使用动态以外的东西吗?

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

Lee*_*Liu 4

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

    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 });                     
    }
Run Code Online (Sandbox Code Playgroud)

通知类别详细信息:

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; }
}
Run Code Online (Sandbox Code Playgroud)

充当嵌套对象的 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; }
}
Run Code Online (Sandbox Code Playgroud)

结果截图:

在此输入图像描述

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