C# Cosmos DB Patch - insert element into child collection
Asked Answered
R

1

5

Trying to add a new item into a parent object's child collection. For example, in the code below, how would one go about adding a new Item to the Items collection?

{
    "id": "SalesOrder2",
    "ponumber": "PO15428132599",
    "OrderDate": "2005-07-01T00:00:00",
    "AccountNumber": "Account2",
    "Items": [
        {
            "Id": 1,
            "OrderQty": 3,
            "ProductCode": "A-123",
            "ProductName": "Product 1",
            "CurrencySymbol": "$",
            "CurrencyCode": "USD",
            "UnitPrice": 17.1,
            "LineTotal": 5.7
        },
        {
            "Id": 2,
            "OrderQty": 2,
            "ProductCode": "A-456",
            "ProductName": "Product 2",
            "CurrencySymbol": "$",
            "CurrencyCode": "USD",
            "UnitPrice": 10,
            "LineTotal": 20
        }
    ],
    "_rid": "BsMkAMc43s4CAAAAAAAAAA==",
    "_self": "dbs/BsMkAA==/colls/BsMkAMc43s4=/docs/BsMkAMc43s4CAAAAAAAAAA==/",
    "_etag": "\"00000000-0000-0000-e136-0dbec04601d7\"",
    "_attachments": "attachments/",
    "_ts": 1637760030
}

Doing something like this:

public async Task AddProduct(Item item)
{
        var response = await CosmosDbContainer.PatchItemAsync<Product>(
        id: "a1dc8286-bb5e-4ac0-beb4-f9f1dfc79711",
        partitionKey:new PartitionKey("a1dc8286-bb5e-4ac0-beb4-f9f1dfc79711"),
        patchOperations: new[] { PatchOperation.Add("/Items", item) });
}

returns the following error:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestApp.Models.Item]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

Passing in a list of Items works, but it replaces all the children, e.g:

public async Task AddProduct(Item item)
{
    var itemList = new List<Item>();
    itemList.Add(item);
    var response = await CosmosDbContainer.PatchItemAsync<Product>(
        id: "a1dc8286-bb5e-4ac0-beb4-f9f1dfc79711",
        partitionKey:new PartitionKey("a1dc8286-bb5e-4ac0-beb4-f9f1dfc79711"),
        patchOperations: new[] { PatchOperation.Add("/Items", ItemList) });
}

Any advice would be greatly appreciated. Thank you in advance!

React answered 18/1, 2022 at 11:53 Comment(0)
F
7

Have you tried passing the Index? You need to use the Add Operation by passing the specific index of the object that you want to update,

 patchOperations: new[] { PatchOperation.Add("/Items/1", item) });

Or do an Append with "-"

 patchOperations: new[] { PatchOperation.Add("/Items/-", item) });
Falk answered 18/1, 2022 at 14:5 Comment(3)
Could you provide an official documentation link for those conventions?Allaround
learn.microsoft.com/en-us/azure/cosmos-db/…Allaround
2 hours looking for this and I never notice the hyphen in the documentation, thank you ... now finally I can restReichel

© 2022 - 2024 — McMap. All rights reserved.