Azure cosmosdb 从文档中提取的PartitionKey不';t与CreateItemAsync上标头中指定的项不匹配

Azure cosmosdb 从文档中提取的PartitionKey不';t与CreateItemAsync上标头中指定的项不匹配,azure-cosmosdb,Azure Cosmosdb,我在使用Microsoft.Azure.Cosmos 3.2.0版时有点问题 跑步时 await this.Container.CreateItemAsync<LogEntity>(logEntity, new PartitionKey("anythingIPutHere")); 等待这个.Container.CreateItemAsync(logEntity,new PartitionKey(“anyThingInputhere”); 它抛出 Microso

我在使用Microsoft.Azure.Cosmos 3.2.0版时有点问题

跑步时

await this.Container.CreateItemAsync<LogEntity>(logEntity, new PartitionKey("anythingIPutHere"));
等待这个.Container.CreateItemAsync(logEntity,new PartitionKey(“anyThingInputhere”);
它抛出

Microsoft.Azure.Cosmos.CosmosException HResult=0x80131500
消息=响应状态代码不表示成功:400子状态: 1001原因:(消息:{“Errors”:[“PartitionKey提取自 文档与标题“]}中指定的文档不匹配

但是如果我把

await this.Container.CreateItemAsync<LogEntity>(logEntity, new PartitionKey(logEntity.Id));
等待this.Container.CreateItemAsync(logEntity,new PartitionKey(logEntity.Id));
它是有效的,而且是唯一有效的情况

我也试过了

  • 将分区键的值作为属性放入对象中
  • 甚至指定
    partitionKey
    JSON属性名,但没有成功

我查看了Microsoft站点上的一些指南,似乎您可以将分区键指定为某个字符串,而不必指定为id或使用对象上的属性名称;那么为什么会发生这种情况呢?

我在创建容器时忽略了这一点

this.Container = await this.Database.CreateContainerIfNotExistsAsync("testContainer", "/id");
我已将
partitionKeyPath
指定为
/id

分区键似乎还必须位于对象上,并且必须具有partitionKeyPath属性名称的json属性,不带/like:

[JsonProperty(PropertyName = "partition")]
public string Partition { get; set; }
如果
partitionKeyPath
/partition

this.Container = await this.Database.CreateContainerIfNotExistsAsync("testContainer", "/partition");

很抱歉,如果这是显而易见的,我刚刚开始使用CosmoDb。

请注意,当您在Azure Portal中创建容器时,也需要指定PartitionKey,您还可以直接引用稍后要插入该容器中的文档的属性。例如,当您的容器将存储
Person
文档,并且
Person
类有一个属性
FirstName
,您可以将门户中的PartitionKey指定为
/FirstName
。在这种情况下,Json注释
[JsonProperty()不需要属性的
。谢谢,这很有帮助!啊,我没有意识到它必须是字符串;我的分区键属性的类型是PartitionKey(这两个属性完全匹配,并且指定正确,一切正常)…将其转换为字符串修复了该问题。非常感谢@brainslaugs83-我已经为此奋斗了一段时间(在您发表此评论之前)今晚以全新的眼光回到它,发现了这个问题,并在10分钟内解决了。有关选择分区键的更多信息-您可以将JSON文档中的任何字段指定为分区键,而不一定是“id”.在创建容器时指定的分区键应该是创建项时传递的键值。在您的情况下,Id是在创建容器时指定的分区键,因此在传递“Id”时它起作用。另请注意-在创建分区键时,以“camelCase”格式创建它。例如,您可以指定“pinCode”作为分区键