1
votes

Attempting to upsert items into Cosmos DB from a .NET Core 3.1 console app on Windows 10 with C#.

JSON document looks like this:

{
        "id": "25217f96-d399-4bb7-b8f1-4a7365cca76c",
        "title": "my title",
        "eventUtc": "2020-09-04T14:16:04+0000" ,
        "listOne":
                        [
                                {"person1" : "james" , "contributorContact" : "" , "contributorTtype" : "contributor"} ,
                                {"person2" : "veena" , "contributorContact" : "" , "contributorTtype" : "contributor"}
                        ]
        ,
        "listTwo" :
                        [
                                "lorem" , "ipsum"  , "dolor" 
                        ] ,
        "synopsis" : "abcdefghi."  }

This document does not exist in the container, but the container exists with one other document already. Partition Key is "id".

This code fails: ...

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

There are not many files, so upserting them individually is what is wanted.

Error message is:

Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: 9c545c05-102f-4ed5-9c6c-e5092ae1671b; Reason: (Message: {"Errors":["One of the specified inputs is invalid"]}....

Where is the error in the code? Based on https://github.com/Azure/azure-cosmos-dotnet-v3/issues/1463 I thought this would work.

Thanks.

1

1 Answers

2
votes

In your provided code, it seems like you're sending the partition key name "id" rather than the id of the item. It should look like:

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

Note using the resolved itemId when providing partition key. Also, you probably want a using statement with your MemoryStream instance.