BccCode.ChangeHistory 0.2.24

There is a newer version of this package available.
See the version list below for details.
dotnet add package BccCode.ChangeHistory --version 0.2.24
                    
NuGet\Install-Package BccCode.ChangeHistory -Version 0.2.24
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BccCode.ChangeHistory" Version="0.2.24" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BccCode.ChangeHistory" Version="0.2.24" />
                    
Directory.Packages.props
<PackageReference Include="BccCode.ChangeHistory" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BccCode.ChangeHistory --version 0.2.24
                    
#r "nuget: BccCode.ChangeHistory, 0.2.24"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BccCode.ChangeHistory@0.2.24
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BccCode.ChangeHistory&version=0.2.24
                    
Install as a Cake Addin
#tool nuget:?package=BccCode.ChangeHistory&version=0.2.24
                    
Install as a Cake Tool

Relational data, with intent and history

Drafted with AI assistance; human review pending before production adoption.

ChangeHistory keeps ordinary relational data: EF Core entities, LINQ and normal transactions. It adds three things.

Added What it gives you
A business event per transaction Why a change happened, who did it, and where it came from
History per entity, by choice Old versions as typed rows with the period they were current, or only a link to the event, or nothing
Valid periods Who held a role on a date, with overlap and coverage enforced by PostgreSQL

You call SaveChangesAsync(). PostgreSQL triggers write the history, so EF saves, bulk updates and plain SQL are all covered. A tracked write without an event is rejected.

A prototype on .NET 11 (C# 15), EF Core 11 and PostgreSQL 18. Npgsql's EF Core provider 11 is still a release candidate (11.0.0-rc.3), and so are the EF Core 11 packages it requires. The packages are released as stable versions anyway, so installing them brings in those release candidates.

How it works, in five steps

1. Derive a context and map your entities. Choose what to track for each.

public sealed class AppDbContext(DbContextOptions<AppDbContext> options, BusinessEventContext events)
    : ChangeHistoryDbContext(options, events)
{
    public DbSet<Person> People => Set<Person>();
    public DbSet<Application> Applications => Set<Application>();
    public DbSet<RoleAssignment> RoleAssignments => Set<RoleAssignment>();

    protected override void ConfigureEntities(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().ToTable("people").TrackHistory();          // events + old values
        modelBuilder.Entity<Application>().ToTable("applications").TrackEvents(); // events only
        modelBuilder.Entity<RoleAssignment>(b =>
        {
            b.ToTable("role_assignments").TrackHistory();
            b.HasValidPeriod().WithoutOverlaps(x => new { x.PersonId, x.LocationId });
        });
    }
}

2. Register it. One dependency scope is one business action.

builder.Services.AddChangeHistory<AppDbContext>(connectionString);

3. Create the database with stock EF migrations. Nothing is written by hand.

dotnet ef migrations add Initial --context AppDbContext --project samples/BccCode.ChangeHistory.Sample
dotnet ef database update --context AppDbContext --project samples/BccCode.ChangeHistory.Sample

The migration contains only EF's own operations. Applying it also creates the event tables, a history table and capture triggers for each history-tracked entity, and the valid-period constraints. Later model changes work the same way, forwards and back.

4. Save a business action. Say what it is, change entities, save once.

// Simplified; the sample's MovedLocation also carries the new address.
public sealed record MovedLocation(Guid AssignmentId, Guid LocationId, DateTime EffectiveOn);

eventCtx.Set(new MovedLocation(assignmentId, waltropId, Period.Utc(2028)));
assignment.ValidAt = Period.Between(assignment.ValidAt.LowerBound, Period.Utc(2028));
db.Add(new RoleAssignment { PersonId = personId, LocationId = waltropId, Role = "SiteManager",
    ValidAt = Period.Between(Period.Utc(2028), Period.Utc(2029)) });
address.City = "Waltrop";
await db.SaveChangesAsync();   // one event, three changes, one transaction

eventCtx is the injected BusinessEventContext. With the hosting addon, HTTP endpoints and Wolverine handlers get it filled in by middleware, so a handler only changes entities.

5. Read what happened through db.History, on the same context.

// The events of one person, newest first.
var timeline = await db.History.EventsFor<Person>(personId)
    .OrderByDescending(e => e.RecordedAt).Take(20).ToListAsync();

// The person and their address as recorded at the oldest of those events,
// or at any time: await db.History.AsOfAsync(time).
await using var past = await db.History.AsOfAsync(timeline[^1].Id);
var then = await past.People.Include(p => p.Address).SingleAsync(p => p.Id == personId);

The walkthrough shows every feature this way, in order.

Words used

The docs and the code use these words with one meaning each.

Word Meaning
Business action One thing a person or system does, such as moving a staff member. One scope, one transaction
Intent The description of the action before it is saved: name, actor, reason, payload. You set it on BusinessEventContext
Business event The stored record of the action: the intent, when it was recorded and where it came from. One per transaction
Link A connection between an event and an entity it concerns. Changed entities are linked automatically
Tracking What is kept for an entity type: history, events only, or nothing
Version The values of a history-tracked entity from one event until the next: numbered 1, 2, 3 ..., with the time it was current from and to
Change A version next to the one before it: before and after
Valid period The business dates a row applies to. Separate from when it was recorded
As of The data as recorded at a time. "At an event" is as of that event's time, including its own changes

Choose what to track

Track Interface Fluent Stored
Events and old values IHistoryTracked .TrackHistory() The current version in the table itself; every earlier version in history.<table>
Events only IEventTracked .TrackEvents() A link in audit.entity_events; no values
Nothing none .TrackNothing() Only the current row
A valid period (independent of the above) IValidDuring .HasValidPeriod() A tstzrange column valid_at

Use the interface or the fluent call; the fluent call wins when both are present. Constraints on valid periods are fluent: .WithoutOverlaps(key) and .WithinPeriodOf<T, TParent>(key).

What is stored

A person is registered (event E1) and later renamed (event E2).

app.people, the current rows:

id display_name version event_id recorded_from
p1 Siri Testperson 2 E2 2027-03-01 10:15

history.people, every earlier version:

id display_name version event_id recorded_from recorded_to ended_by
p1 Siri Hansen 1 E1 2026-09-12 08:30 2027-03-01 10:15 E2
Also Content
history.people_versions A view of both tables: all versions
audit.events E1 and E2: name, actor, reason, typed payload, trace, time
audit.entity_events Which events concern which entity: E1 inserted p1, E2 updated p1. Also the links a handler adds with LinkTo

The data as recorded at a time T is every version with recorded_from <= T and no recorded_to, or one after T. That is plain SQL:

SELECT * FROM history.people_versions
WHERE recorded_from <= '2027-01-01' AND (recorded_to IS NULL OR recorded_to > '2027-01-01');

A version has the entity's own typed columns. JSON is used only for the event payload and the trace. More queries by hand.

Compared with event sourcing

Here, relational rows are the source of current state and events explain the changes. Marten makes events the source of state and rebuilds state through projections. ChangeHistory fits relational editing, joins and audit history. Event sourcing fits replaying authoritative business facts.

Limits

  • One PostgreSQL database, version 18. Not tested on 19.
  • History holds one version per event, not the steps inside a transaction.
  • A migration locks the tables it changes while it runs; other tables stay available.
  • No production authorization, data-retention policy or message transport recovery. The Wolverine outbox adapter is tested against PostgreSQL only.
  • Normal .NET publishing only; Native AOT is not supported.
  • Only the database users you name may write events, also imported ones with a past time: audit.grant_application (database users).
  • The library's SQL is numbered steps (Sql/0001_audit.sql, ...). A migration applies the steps a database has not had, once each, so a fresh install and an upgrade end the same (migrations).
  • A historical context (AsOfAsync) shares the connection of the context it came from: run one query at a time across both, and dispose the historical one before its source. Its queries, also FromSql and IgnoreQueryFilters(), keep the time boundary.

Findings and decisions of the November 2026 review are in notes/review-2026-11.md.

The full list is in the reference.

Projects

Project What it is
src/BccCode.ChangeHistory The library. A package: events, history, valid periods, reads, erase and redact. Needs only Npgsql's EF Core provider
src/BccCode.ChangeHistory.Hosting Optional package for ASP.NET Core and Wolverine: intent from requests and messages, save and publish together
samples/BccCode.ChangeHistory.Sample The sample model, its migrations, the console demo and the benchmark
samples/BccCode.ChangeHistory.Sample.Http Example HTTP endpoints on the sample model
tests/BccCode.ChangeHistory.Tests Integration tests on real PostgreSQL

To use it in another project, reference BccCode.ChangeHistory (and BccCode.ChangeHistory.Hosting if you use Wolverine or the HTTP middleware), derive your context from ChangeHistoryDbContext and follow the five steps above. Both are on nuget.org under the Apache 2.0 licence; dotnet pack BccCode.ChangeHistory.slnx -c Release builds them locally. A merge to main that changes src/, the build settings or the version file publishes a new version 0.2.<run> automatically; docs, tests and samples alone do not. A beta is published by starting the ChangeHistory workflow by hand with beta. The docs in docs/ are published at developer.bcc.no with the rest of this repository's docs.

Run it

Everything needed is in this folder. Install Docker and the .NET SDK pinned in global.json, and run from here.

The tests start their own PostgreSQL 18 container and remove it afterwards:

dotnet test BccCode.ChangeHistory.slnx

The demo, the benchmark and dotnet ef use the database in compose.yaml:

docker compose up -d --wait
dotnet tool restore
dotnet ef database update --context AppDbContext --project samples/BccCode.ChangeHistory.Sample
dotnet run --project samples/BccCode.ChangeHistory.Sample -- demo
dotnet run -c Release --project samples/BccCode.ChangeHistory.Sample -- benchmark 200
Local connection Value
PostgreSQL (Compose) 127.0.0.1:55432, database changehistory
Migration and maintenance owner postgres / prototype
Application user changehistory_app / prototype. Created by the demo and the tests; the library itself creates no database users
Overrides OWNER_CONNECTION, APP_CONNECTION. With OWNER_CONNECTION set, the tests use that server and start no container

The credentials are for the local container only. The demo and benchmark accept only changehistory or changehistory_demo_* databases. Each test creates and drops its own changehistory_test_* database.

Documentation

Read For
Walkthrough Every feature once, in order, with code
HTTP and Wolverine Intent from endpoints and messages, automatic save, outbox
Operations Concurrency and retries, schema changes, erasing and redacting data
Reference The whole API in one table, the tables and SQL by hand, guarantees, import, migrations, performance, limits

Licence

Apache 2.0.

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on BccCode.ChangeHistory:

Package Downloads
BccCode.Privacy.Hosting

One AddPrivacy() for BCC Privacy: the EF Core, ASP.NET Core and Wolverine packages wired together, defaults per environment, the privacy document at /.well-known/bcc-privacy, and the application's processes and data items pushed to the Privacy API at deploy.

BccCode.ChangeHistory.Hosting

ASP.NET Core and Wolverine integration for BccCode.ChangeHistory: the business intent from HTTP requests and messages, and saving and publishing in one transaction.

BccCode.Privacy.ChangeHistory

Connects BCC Privacy for EF Core and BccCode.ChangeHistory on one model: events, links, changes and history versions are read per organisation, like the current rows.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.4.70 69 11/19/2026
0.4.68 114 11/19/2026
0.4.66 56 11/19/2026
0.4.64 290 11/18/2026
0.4.63 73 11/18/2026
0.4.60 78 11/18/2026
0.4.58 78 11/18/2026
0.4.57 71 11/18/2026
0.4.54 71 11/18/2026
0.4.52 77 11/18/2026
0.4.51 76 11/18/2026
0.4.50 82 11/18/2026
0.4.49 75 11/18/2026
0.4.43 83 11/18/2026
0.3.31 111 11/16/2026
0.2.28 70 11/15/2026
0.2.26 71 11/15/2026
0.2.24 66 11/15/2026
0.2.22-preview 57 11/15/2026
0.1.15 103 11/15/2026
Loading failed