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

C# 在Cosmos DB中存储具有动态属性的对象,c#,.net,azure-cosmosdb,C#,.net,Azure Cosmosdb,我有一个消息处理器,我想用一个已知模式的包装器获取一块json,但其属性是一个动态对象,如下所示: public class NotificationDetails { [JsonProperty(PropertyName = "id")] public string NotificationID { get; set; } public DateTime? DateCreated { get; set; } public DateTime? DateSent {

我有一个消息处理器,我想用一个已知模式的包装器获取一块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))”匹配的最佳重载方法具有一些无效参数

我想我可以在这些文件中投入任何东西。我做错了什么?我是否应该对此模型属性使用动态以外的内容


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

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

    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; }
}
结果截图:


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

您是否使用了cosmos sql api?我找不到任何sdk的方法:CreateItemAsync(t);我正在使用Microsoft.Azure.DocumentDB nuget包。我正在包装DocumentClient.CreateDocumentSync方法。我抄错了行。我会把我的问题修改得更准确些,它超级聪明。。。。我将DocumentDB封装在自己的项目中,并将DocumentClient封装在一个单一存储库中。。。。当我将同一个NotificationDetails类复制到单元测试项目中时,它可以工作。。。。但是,从我引用此解决方案的webapi项目来看,它不。。。。我会进一步测试