问题描述
尝试在Windows 10上使用C#从.NET Core 3.1控制台应用程序向Cosmos DB中插入项目。
JSON文档如下所示:
{
"id": "25217f96-d399-4bb7-b8f1-4a7365cca76c","title": "my title","eventUtc": "2020-09-04T14:16:04+0000","listOne":
[
{"person1" : "james","contributorContact" : "","contributorTtype" : "contributor"},{"person2" : "veena","contributorTtype" : "contributor"}
],"listTwo" :
[
"lorem","ipsum","dolor"
],"synopsis" : "abcdefghi." }
此文档在容器中不存在,但是该容器已经与另一个文档一起存在。分区键是“ id”。
此代码失败: ...
foreach (var fileOne in Directory.GetFiles(fileLoc))
{
MemoryStream stream = new MemoryStream();
await System.Text.Json.JsonSerializer.SerializeAsync(stream,File.ReadAllText(fileOne));
var response = await cosmosContainer.UpsertItemStreamAsync(stream,new PartitionKey("id"));
}
文件不多,因此需要单独上载它们。
错误消息是:
响应状态代码不表示成功:BadRequest(400); 子状态:0;活动编号:9c545c05-102f-4ed5-9c6c-e5092ae1671b; 原因:(消息:{“错误”:[“指定的输入之一是 无效“]}。...
代码中的错误在哪里?基于https://github.com/Azure/azure-cosmos-dotnet-v3/issues/1463,我认为这可行。
谢谢。
解决方法
在您提供的代码中,似乎您正在发送分区键名称“ id”,而不是项目的id
。看起来应该像这样:
foreach (var fileOne in Directory.GetFiles(fileLoc))
{
MemoryStream stream = new MemoryStream();
await System.Text.Json.JsonSerializer.SerializeAsync(stream,File.ReadAllText(fileOne));
string itemId = // Extract ID from item
var response = await cosmosContainer.UpsertItemStreamAsync(stream,new PartitionKey(itemId));
}
请注意在提供分区键时使用解析的itemId
。另外,您可能希望在MemoryStream实例中使用using
语句。