Condividi tramite


PatchOperation.Replace<T>(String, T) Method

Definition

Create PatchOperation<T> to replace a value.

public static Microsoft.Azure.Cosmos.PatchOperation Replace<T> (string path, T value);
static member Replace : string * 'T -> Microsoft.Azure.Cosmos.PatchOperation
Public Shared Function Replace(Of T) (path As String, value As T) As PatchOperation

Type Parameters

T

Type of value

Parameters

path
String

Target location reference.

value
T

The new value.

Returns

PatchOperation instance for specified input.

Examples

Example 1: Replace Operation on a Non-existent Property

ToDoActivity toDoActivity = await this.container.ReadItemAsync<ToDoActivity>("id", new PartitionKey("partitionKey"));

/* toDoActivity = {
    "id" : "someId",
    "status" : "someStatusPK",
    "description" : "someDescription",
    "frequency" : 7
}*/

This example illustrates what happens when a Replace operation is attempted on a property that does not exist.
In this case, trying to replace the "priority" property, which is not present in the original ToDoActivity item, results in an HTTP 400 BadRequest.

List<PatchOperation> patchOperations = new List<PatchOperation>()
{
    PatchOperation.Replace("/priority", "High")
};

try
{
    ItemResponse<ToDoActivity> item = await this.container.PatchItemAsync<ToDoActivity>(toDoActivity.id, new PartitionKey(toDoActivity.status), patchOperations);
}
catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.BadRequest)
{
    ...
}

Remarks

The Replace operation is similar to Set in that it updates a field's value, but differs in one crucial way: Replace only updates an existing field. If the field is absent, Replace will fail and throw a **400 BadRequest** (HTTP status code 400). In contrast, Set will either update the existing field or create a new one if it does not exist. Users should be aware that Replace follows strict semantics and will not add new fields, unlike Set, which is more flexible.

Applies to