Appearance
Optimistic concurrency
An entity can opt in to a version token. The version is 1 on insert and grows by 1 on every saved update, so a client that read version 3 can only change the row while the row is still at version 3. Nothing changes for an entity that does not implement IVersioned.
Opting in
csharp
public sealed class Order : IVersioned
{
public Guid Id { get; private set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public int Version { get; private set; } // set by the persistence pipeline
}
// OnModelCreating: call it last, so every entity type is already known.
modelBuilder.ApplyVersionedConcurrency();
// Registration
services.AddGrydVersionedEntities();
services.AddDbContext<AppDbContext>((provider, options) => options
.UseNpgsql(connectionString)
.UseGrydAuditableEntities(provider)
.UseGrydVersionedEntities(provider)); // the order against the audit interceptor does not matterThe token is applied to root, non-owned entity types only. A soft delete (an entity that inherits BaseEntity) counts as an update and moves the version; a physical delete is not stamped.
Expected version from the client
csharp
var order = await context.Orders.SingleAsync(o => o.Id == id, cancellationToken);
context.ExpectVersion(order, request.ExpectedVersion); // before changing the entity; must be >= 1
order.Name = request.Name;
await context.SaveChangesAsync(cancellationToken);A stored version different from the expected one makes SaveChanges throw DbUpdateConcurrencyException. ExpectVersion also protects a physical delete: the DELETE only runs for the expected version.
Conflict response
DbUpdateConcurrencyException is answered as HTTP 409 with the code DB_CONCURRENCY_CONFLICT, with or without the GrydAuth module in the host. The same answer covers a write barred by ProtectTenantWrites (another tenant's row) and a row removed between the read and the write. The core handler logs it as a warning with the entity type names only, never values.
The errorType of the core answer is ExceptionMessages.ErrorTypes.Conflict; the GrydAuth handler answers first in hosts that have it and uses its own errorType. The code is the same in both.
Migrating a table with rows
The token does not change the schema, but the column must exist. For a table that already has rows:
csharp
migrationBuilder.AddColumn<int>(name: "Version", table: "Orders", nullable: false, defaultValue: 1);Do not set HasDefaultValue in the model: the stamper writes 1 on insert. On PostgreSQL 11 and later a constant default does not rewrite the table.
Limits
- Only the marked entity moves its version: a change only in a child of the aggregate, or only in an owned type stored in the same table, does not raise the aggregate's version.
ExecuteUpdateandExecuteDeletedo not pass through the stamper.- The client must send the version it read;
If-MatchandETagheaders are not handled.