Skip to content

The search box knows all the secrets -- try it!

Polecat is part of the Critter Stack ecosystem.

JasperFx Logo JasperFx provides formal support for Polecat and other Critter Stack libraries. Please check our Support Plans for more details.

Partial Updates / Patching ​

Polecat provides a patching API for making targeted updates to documents without loading and re-saving the entire document. Under the hood, this uses SQL Server's JSON_MODIFY() function.

Basic Usage ​

cs
// Patch a document by ID
session.Patch<Order>(orderId)
    .Set(x => x.Status, "Shipped");

await session.SaveChangesAsync();

Available Operations ​

Set a Value ​

cs
session.Patch<Order>(orderId)
    .Set(x => x.Status, "Completed")
    .Set(x => x.ShippedDate, DateTimeOffset.UtcNow);

Set nested properties:

cs
session.Patch<Order>(orderId)
    .Set(x => x.Address.City, "New York");

If Address is missing or null, it is created, however many levels are missing. A parent that holds some other value, such as a number, is left alone. This goes for everything that writes a value, including Increment, Append, Insert and Duplicate. Delete and Remove never create anything.

Set a dictionary entry with its indexer, whatever the type of the key:

cs
session.Patch<Order>(orderId)
    .Set(x => x.NotesByDay[new DateOnly(2026, 11, 2)], "Shipped")
    .Set(x => x.Labels["a.key with spaces"], "value");

The key is written exactly the way System.Text.Json writes it in the document, including any DictionaryKeyPolicy and Encoder you have configured, so this finds the stored entry on any host culture. PropertyNamingPolicy is not applied to a key, because the serializer doesn't apply it either. An index into a list, as in x.Items[0], isn't supported and throws NotSupportedException.

Increment a Numeric Value ​

cs
session.Patch<Order>(orderId)
    .Increment(x => x.ItemCount, 1);

// Decrement by using a negative value
session.Patch<Order>(orderId)
    .Increment(x => x.ItemCount, -1);

Append to a Collection ​

cs
session.Patch<Order>(orderId)
    .Append(x => x.Tags, "priority");

Append only if the value doesn't already exist:

cs
session.Patch<Order>(orderId)
    .AppendIfNotExists(x => x.Tags, "priority");

Insert at a Specific Position ​

cs
session.Patch<Order>(orderId)
    .Insert(x => x.Tags, "urgent", index: 0);

Remove from a Collection ​

cs
session.Patch<Order>(orderId)
    .Remove(x => x.Tags, "obsolete");

Remove, AppendIfNotExists and InsertIfNotExists match an element exactly, whatever the database's collation: "ABC" is not "abc", "abc " is not "abc", and the string "1" is not the number 1.

Duplicate a Value ​

Copy a value to multiple destinations:

cs
session.Patch<Order>(orderId)
    .Duplicate(x => x.BillingAddress, x => x.ShippingAddress);

Rename a Property ​

cs
session.Patch<Order>(orderId)
    .Rename("oldPropertyName", x => x.NewPropertyName);

If a document has no oldPropertyName, its NewPropertyName is left as it is, so a rename can safely run again over documents that already have the new shape.

Delete a Property ​

cs
session.Patch<Order>(orderId)
    .Delete("obsoleteField");

// Or via expression
session.Patch<Order>(orderId)
    .Delete(x => x.ObsoleteField);

Patching with a Where Clause ​

Apply patches to multiple documents matching a condition:

cs
session.Patch<Order>(x => x.Status == "Pending")
    .Set(x => x.Status, "Cancelled");

await session.SaveChangesAsync();

The condition is evaluated once, before any action runs, so a patch can change the member it filters on and every action still reaches the same documents:

cs
session.Patch<Order>(x => x.Status == "Pending")
    .Set(x => x.Status, "Cancelled")
    .Set(x => x.CancelledBy, "system");

How It Works ​

Each patch operation generates a SQL UPDATE statement using JSON_MODIFY():

sql
UPDATE pc_doc_order
SET data = JSON_MODIFY(CAST(data AS nvarchar(max)), N'$.status', 'Shipped')
WHERE id = @id

For collection operations, Polecat uses OPENJSON and STRING_AGG to manipulate JSON arrays.

TIP

Patching is more efficient than loading, modifying, and re-saving a document because only the changed values are sent to the database, and it doesn't require reading the full document first.

Patching and the Native json Type ​

The CAST above is deliberate. On SQL Server 2025 RTM-CU5, a JSON_MODIFY that adds a key directly to a json value leaves it in a state where the next JSON_MODIFY through an object can go wrong. Which way depends on the document's keys: the write can land on another member of the document, disappear, or leave a member corrupted, so that reading it fails with "Encountered corrupted JSON type" and a plain SELECT of the column drops the connection. Until that second write the row reads back correctly, and DBCC CHECKTABLE doesn't report it, even with EXTENDED_LOGICAL_CHECKS. Working on text avoids this, and the next patch to a row that an earlier version left in that state puts it right. A write that has already gone astray can't be undone this way.

The cost is a full parse of the document for each patch operation, so the time for one update grows with its size. Measured per update on one server:

Document sizeDirectly on jsonThrough text
1 KB0.7 ms0.9 ms
10 KB1.0 ms2.8 ms
100 KB1.7 ms14.8 ms
1 MB4.1 ms170 ms

nvarchar(max) storage pays none of this.

Finding Documents an Earlier Version Damaged ​

Through 5.47.0 patches ran directly on json, so a store using the native type may hold documents those two writes damaged. When the write landed on a document's id, its JSON id no longer matches the id column, and it won't load. Polecat can find those:

cs
// One document type
var damaged = await store.Advanced.FindDocumentsWithMismatchedIdsAsync<Order>();

// Every document type the store is configured with
var everything = await store.Advanced.FindDocumentsWithMismatchedIdsAsync();

foreach (var byType in everything.GroupBy(x => x.DocumentType))
{
    logger.LogWarning("{Count} damaged {Type} documents", byType.Count(), byType.Key.Name);
}

It's read-only and safe to run on a live store. It compares the two on the server, a page at a time, so no document bodies come back and a large table costs one pass of the server's time. Pass a page size if a page of the default 5,000 runs out of CommandTimeout. Strong-typed and string ids work, soft-deleted documents are included, and it covers every tenant under conjoined tenancy and every database under database-per-tenant. A document type that leaves its id out of the body is never reported.

Each DocumentIdMismatch gives the Id from the column, which is right, and StoredId, what the body holds instead. IsCorrupted is true when the server can't read the stored id at all.

WARNING

This only finds damage to the id. The same write can land on any member of a document, or vanish, and nothing stored says what those members should have held, so an empty result doesn't prove a document is intact. If you can rebuild a document, from a projection's events or from a backup, that is the only general answer. DBCC CHECKTABLE ... WITH EXTENDED_LOGICAL_CHECKS reports corrupted rows, which this finds only when the corrupted member is the id, but not a write that landed on the wrong member.

A document whose id was overwritten can be put right from its column, though what the patch meant to write is still lost. On a table with a uniqueidentifier id:

sql
UPDATE [dbo].[pc_doc_order]
SET data = JSON_MODIFY(CAST(data AS nvarchar(max)), '$.id', LOWER(CONVERT(nvarchar(36), id)))
WHERE id = @id;

A corrupted row can't be repaired in place, because every JSON_MODIFY of it fails. Replace the whole body, by storing the document again from its source, or delete it.

Released under the MIT License.