BccCode.Privacy.EntityFrameworkCore 0.9.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package BccCode.Privacy.EntityFrameworkCore --version 0.9.2
                    
NuGet\Install-Package BccCode.Privacy.EntityFrameworkCore -Version 0.9.2
                    
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.Privacy.EntityFrameworkCore" Version="0.9.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BccCode.Privacy.EntityFrameworkCore" Version="0.9.2" />
                    
Directory.Packages.props
<PackageReference Include="BccCode.Privacy.EntityFrameworkCore" />
                    
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.Privacy.EntityFrameworkCore --version 0.9.2
                    
#r "nuget: BccCode.Privacy.EntityFrameworkCore, 0.9.2"
                    
#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.Privacy.EntityFrameworkCore@0.9.2
                    
#: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.Privacy.EntityFrameworkCore&version=0.9.2
                    
Install as a Cake Addin
#tool nuget:?package=BccCode.Privacy.EntityFrameworkCore&version=0.9.2
                    
Install as a Cake Tool

BccCode.Privacy.EntityFrameworkCore

Part of the BCC Privacy package family, which all share one version:

Package Contents
BccCode.Privacy The framework-neutral core: processes, groups, data items, bases, typed keys, PrivacyScope, the privacy document, BasisChanged. No framework dependency; data items are Microsoft.Extensions.Compliance data classifications, so they are redacted in logs
BccCode.Privacy.EntityFrameworkCore This package: read filters, read views, row-level security, save guards and migrations for EF Core and PostgreSQL. Depends on the core
BccCode.Privacy.AspNetCore The scope per request, the endpoint's declared process, refusal of endpoints that read personal data without one, masking of items in JSON responses. Depends on the core
BccCode.Privacy.Wolverine The scope on message envelopes and before every handler; refusal of handlers that read personal data without a process; bases' moments applied as they come and BasisChanged published. Depends on the core
BccCode.Privacy.Hosting One AddPrivacy<TContext>() wiring the above; defaults per environment; the privacy document at /.well-known/bcc-privacy; the application's processes and items checked at start-up against the revision the deploy accepted; nothing published at start-up. Depends on all of the above and BccCode.Privacy.Client

The core's types are in the namespace BccCode.Privacy; this package's in BccCode.Privacy.EntityFrameworkCore. Since 0.2.0 an application needs both using directives.

Purpose-bound access to personal data in EF Core and PostgreSQL. A row is returned only when a basis covers its person for the organisation and process of the request; other organisations see only the data items shared with them. Queries and saves stay ordinary EF Core; the package adds a query filter, a save guard, and read views generated by your normal migrations.

Design: docs/architecture-proposal, pages 00 and 16. Version 0.x: the API will change. Licence: Apache 2.0. Since 0.5 it targets .NET 10 (LTS), EF Core 10 and Npgsql's EF Core 10 provider, all stable releases, on PostgreSQL 18, as BccCode.ChangeHistory does. 0.4 targeted .NET 11 and the EF Core 11 release candidates; it used nothing from them, so 0.5 went back to .NET 10. Applications on .NET 11 can use 0.5 too.

Use

using BccCode.Privacy;
using BccCode.Privacy.EntityFrameworkCore;

public sealed class AppDbContext(DbContextOptions<AppDbContext> options, PrivacyScope scope)
    : DbContext(options), IPrivacyDbContext
{
    public PrivacyScope Scope { get; } = scope;            // one per request; fixed at the first command
    public PrivacyRules Rules { get; } = new PrivacyRules()
        .Group<Membership>("members", m => m.PersonId, m => m.OrganisationId, m => m.Id, activeWhile: m => m.Ended == null)
        .Process(1, new("membership.register")).Covers<PersonProfile>().Done();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.UsePrivacy();
        b.Entity<PersonProfile>(e =>
        {
            e.Personal(this, subject: x => x.PersonId, organisation: x => x.OrganisationId);
            e.Item(Items.Name, sortable: true, x => x.FirstName, x => x.LastName);   // shareable, by item
        });
    }
}

// options: .UseNpgsql(...).UsePrivacy()

On other organisations' rows the read view returns a column that is not an item as NULL, except bookkeeping: the row's identifiers, concurrency tokens and row versions (xmin), ChangeHistory's version, event_id and recorded_from, and any property marked .NotPersonalData(), which are returned raw (F8).

Declare item keys once (public static readonly ItemKey Name = new("name");). A shareable entity maps at most 64 items, each once, and each column to one item; anything else fails when the model is built (LIB-13). A special-category table adds .EnforcedInDatabase(): PostgreSQL row-level security, so even raw SQL sees only the acting organisation's rows. Such a table cannot also be shared.

With ChangeHistory

The package writes usable only on rows whose flag changes (F2), so a basis change rewrites no unchanged row. The ChangeHistory integration itself (excluding usable and reader_org from versioning, event owners, event and history filters) is the typed adapter BccCode.Privacy.ChangeHistory (review A10), registered by Hosting.

Foreign keys between personal entities

Foreign keys and navigations between personal entities are allowed within one organisation (F14), so Include and ChangeHistory's dependent selection work. Put the organisation in the key, so the database refuses a row that points at another organisation's row:

b.Entity<PersonProfile>().HasAlternateKey(p => new { p.Id, p.OrganisationId });
b.Entity<PersonProfile>().HasMany(p => p.Addresses).WithOne()
    .HasForeignKey(a => new { a.ProfileId, a.OrganisationId }).HasPrincipalKey(p => new { p.Id, p.OrganisationId });

A foreign key between personal entities that does not carry the organisation is refused at the context's first command, naming the fix; PrivacyForeignKeys.Violations(model) lists them, for a start-up check. Never a foreign key to another organisation's rows.

Cases

A process may work per case (LIB-11), such as an A-team application: two applications of one person are independent.

.Group<Application>("applicants", a => a.PersonId, a => a.OrganisationId, a => a.Id, activeWhile: a => a.Closed == null)
.Process(4, new("ateam.reference_review")).CaseKey<Application>(a => a.Id)
    .Covers<Application>().Covers<ReferenceStatement>().Covers<PersonProfile>().Done();
// model: e.Personal(...).Case(x => x.ApplicationId);   on the case fact itself: .Case(x => x.Id)

Under such a process, a row of an entity marked with Case(...) is usable only for its own case: a person basis whose Source is PrivacyCase.Source(caseId), or a group basis whose group is decided by the case fact while that fact is active. Closing one application hides its rows and leaves the other's visible. Entities without Case(...) (profiles) stay on the person path. Without a case key nothing changes. Retention and deletion per case follow with the deletion job (LIB-3).

Groups that depend on the time

A group decided by a fact with a valid period declares activeAt instead of activeWhile (F4), and is evaluated at the context's clock, in SQL and in memory:

.Group<Membership>("members", m => m.PersonId, m => m.OrganisationId, m => m.Id,
    activeAt: (m, now) => m.Started <= DateOnly.FromDateTime(now) && (m.Ended == null || DateOnly.FromDateTime(now) < m.Ended))

A date that passes later takes effect when the person's rows are next derived. A static group can be dated too: StaticGroup("volunteers", dated: true) counts members for Since <= now < Until, and each member's future date has a moment in privacy.member_boundary, applied by ApplyDueAsync. Upgrading to this version needs a migration (shared_access."Ends" and privacy.member_boundary).

Retention, failures and end times

  • A basis with Allows = "keep" is retain-only: it never makes a row usable or shared (LIB-12). Retained rows are hidden from ordinary queries and included per query: db.Memberships.IncludeRetained().Where(...) returns the organisation's usable rows and its retained ones (never another organisation's); db.IsRetained(row) tells them apart; writing a retained row is refused outside PrivacyMaintenance. Each personal entity has two named filters: the organisation (readership) filter, never relaxed, and its own retention filter (PrivacyRetention:<type>), which IncludeRetained() relaxes on its own root only; every other root in the query keeps both. Any other IgnoreQueryFilters on a shareable entity is refused. For a retained row's history, take its ids from the same query and read the versions with IgnoreQueryFilters() (F16).
  • A failing moment is rolled back, logged and counted (bcc.privacy.moments.failed); ApplyDueAsync applies the next ones, and the failed one stays pending.
  • A disclosure stops at its end time with no job run: the read views' shared branches test shared_access."Ends", the earliest end of the disclosing bases.

Metrics (meter BccCode.Privacy): bcc.privacy.moments.failed, bcc.privacy.moments.oldest_due_age and bcc.privacy.events.oldest_unpublished_age (seconds, updated by ApplyDueAsync and PrivacyBoundaries.StatusAsync).

Grants for the runtime role

Run as the owner, after Migrate() (as ChangeHistory's audit.grant_application):

await PrivacyGrants.GrantApplicationAsync(ownerContext, "app_runtime");   // or: SELECT privacy.grant_application('app_runtime');

It grants the role the privacy schema's tables and sequences, SELECT on the read views, and default privileges, so a view a later migration recreates keeps its grant; with modelTables (default) also DML on the model's own tables. Migrations create the function privacy.grant_application(role). Idempotent (F5).

Versions shared with ChangeHistory

An application that uses BccCode.ChangeHistory with these packages runs one EF Core model, so both must resolve the same EF Core and Npgsql versions. The libraries pin EF Core 10.0.15 (Microsoft.EntityFrameworkCore.Relational, .Design) and Npgsql's EF Core provider 10.0.3 in libraries/dotnet/Directory.Packages.props. ChangeHistory 0.3.31 depends on the same provider 10.0.3, which brings EF Core 10.0.4; the application then resolves 10.0.15 for both. Pin EF Core 10.0.15 in the application too (or take a ChangeHistory release built on 10.0.15) so the EF internal services both packages customise come from one version.

Supported operations

Each behaviour below is covered by a test in BccCode.Privacy.EntityFrameworkCore.Tests.

Operation Behaviour
LINQ reads: Where, OrderBy, Skip/Take, Count, joins, projections Own rows, plus shared rows with only the shared items; ordering and paging cover both
A filter or sort on an item not shared Reveals nothing: the value is null for that row
A masked item projected into a DTO Null
Include over a navigation between personal entities Own related rows; another organisation's related rows only if that table is shared too
Tracked and AsNoTracking reads of one row in one context Agree; identity resolution as usual
Edit an own row read through a view Saved to the table
Edit a row of another organisation read through the filter Refused
Update, Attach or Remove of another organisation's row by its key, without loading it Refused, with the fix: the organisation is a concurrency token, so the UPDATE or DELETE matches no row (since 0.5.2)
A concurrency conflict on a row of an own table A personal table whose only concurrency token is the organisation: refused, as the row belongs to another organisation or no longer exists. With concurrency tokens of your own: EF's DbUpdateConcurrencyException. Either way the save rolls back and the context can save again
Insert a row without a basis for its person Refused, with the fix
Write under a process that does not cover the row Refused, with the fix: the entity must be one the active process covers, an insert needs a basis for that process, and every UPDATE and DELETE also carries AND (usable & @bit) <> 0, so an attached row the process does not cover matches nothing. A missing or undeclared process is refused. PrivacyMaintenance.Begin(db, reason) lifts the process check (not the organisation check) for logged lifecycle work
Change a row's person or organisation, or write usable Refused
SaveChangesAsync Guards run; derived state follows in the same transaction. One save is one save: the package writes moments, shared access and flags with single statements, never a nested SaveChanges, so it composes with another package that hooks the save (ChangeHistory). It uses the caller's transaction when there is one (the application's or ChangeHistory's), and opens one otherwise
SaveChanges() (synchronous) Refused: use SaveChangesAsync
ExecuteUpdate / ExecuteDelete Limited to own usable rows. They do not run the save guard: do not use them on identifiers, usable, bases or group facts (an analyser and a runtime guard follow in LIB-6)
IgnoreQueryFilters on a shareable table Refused, with the fix
IgnoreQueryFilters on other tables, raw SQL Not guarded yet (LIB-6); a table with EnforcedInDatabase() is still limited by PostgreSQL
Changing the scope after the context's first command Refused: one context, one organisation and process
Migrate() at every start Safe: the package's steps run only in the application's own migrations
A migration Views the package generated are listed in privacy.read_view; only those are touched, and only when their definition changed. Added columns: replaced in place (oid, grants and dependent views kept). Otherwise dropped and created; if another object depends on the view, the migration stops and names it
An upgrade or rollback while others read No errors: the migration locks the views first, so reads wait for it
Two overlapping periods of one share in privacy.shared_access Rejected by PostgreSQL 18: UNIQUE (..., "Period" WITHOUT OVERLAPS) on a generated ["Since", "Until") column, added by your next migration (also on databases migrated with 0.2 or 0.3). Needs the btree_gist extension: created if missing, or the migration stops naming the fix

Starts and ends of bases: tested, and planned

Behaviour In this package Planned
A basis counts only from its start to its end Tested: one rule, an injectable clock —
A start or end takes effect at its moment Tested when PrivacyBoundaries.ApplyDueAsync is called; nothing calls it on its own BccCode.Privacy.Wolverine (PublishPrivacyMoments()): a pass at the next pending moment, and at least every 10 s; LIB-3: nightly rebuild as backstop
The event for a moment is not lost Tested: stored in the outbox (privacy.basis_event) in the same transaction; PublishAsync hands it out at least once, with a stable id BccCode.Privacy.Wolverine: published through Wolverine; receivers deduplicate on the id
Two workers apply a moment once Tested: an atomic claim —
A changed, withdrawn or deleted basis leaves no active moment Tested LIB-3: the same for static group members
Maximum staleness when the scheduler is down Ages exported as metrics (StatusAsync); access is not yet stopped past a limit LIB-3, LIB-6: 5-minute limit, alert, shared reads stop past it
Bulk writes keep the derived state Not built: the save guard covers SaveChanges only LIB-6: guarded bulk API, analyser, runtime guard; trusted-code assumption (page 23, F3)

Develop

Needs the .NET SDK from global.json and Docker (the tests start PostgreSQL 18 through Aspire).

dotnet test --project libraries/dotnet/BccCode.Privacy.EntityFrameworkCore.Tests

The sample application and its migrations are in the test project (Sample/). After changing the sample model, add a migration from libraries/dotnet:

dotnet tool restore
dotnet ef migrations add <Name> --project BccCode.Privacy.EntityFrameworkCore.Tests --output-dir Sample/Migrations

Published by .github/workflows/libraries-dotnet-publish.yml: every package of the family is packed and pushed together, with one version, on a merge to main that changes libraries/dotnet. The version comes from git tags, as for BccCode.Privacy.Client (sdk-dotnet-publish.yml, tag prefix sdk-dotnet-v) and bcc-core-api's SDK: paulhatch/semantic-version with the tag prefix libraries-dotnet-v, as <major>.<minor>.<patch>. Each release from main is tagged libraries-dotnet-v<version> (a GitHub release) by the workflow. The next release is the patch after it, unless a commit since the tag is a feat: (next minor) or has !: or BREAKING CHANGE: (next major), the action's defaults. A tag libraries-dotnet-v<major>.<minor>.0 on main also sets the version. A run started by hand on a branch publishes <version>-beta.<run> from the nuget-beta environment. While no libraries-dotnet-v tag exists, the version is 0.5.0; a version below 0.5.0 fails the run. A new package joins the family by adding its project to PROJECTS in the workflow (and, on nuget.org, a trusted-publishing policy if the existing one does not cover the new id). 0.1.0 was BccCode.Privacy.EntityFrameworkCore alone; 0.2.0 was the first release of the family; 0.3 adds the ASP.NET Core and Wolverine packages; 0.4 moves the family to .NET 11, EF Core 11 and Npgsql 11, and adds the Hosting package; 0.5 moves it back to .NET 10, EF Core 10 and Npgsql 10 (stable releases), with the same behaviour. 0.5.2 closes a cross-organisation write: an Update, Attach or Remove of another organisation's row by its key, without loading it, was written. Personal(...) now makes the organisation a concurrency token, the save guard checks its original value, and a save that fails on a concurrency conflict now rolls back its transaction (before, the context's later saves were not committed). No migration is needed. 0.6: Hosting no longer pushes to Privacy at start-up; it checks the definitions against BccPrivacy:AcceptedRevision (LIB-15, Hosting release note).

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on BccCode.Privacy.EntityFrameworkCore:

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.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.13.3 59 11/19/2026
0.13.2 54 11/19/2026
0.13.1 60 11/19/2026
0.13.0 54 11/19/2026
0.12.0 57 11/19/2026
0.11.0 57 11/19/2026
0.10.0 55 11/18/2026
0.9.2 57 11/18/2026
0.9.1 58 11/18/2026
0.9.0 47 11/18/2026
0.8.1 52 11/18/2026
0.8.0 59 11/18/2026
0.7.0 49 11/18/2026
0.6.2 55 11/18/2026
0.6.1 49 11/18/2026
0.6.0 51 11/18/2026
0.5.7 54 11/18/2026
0.5.6 54 11/18/2026
0.5.5 58 11/18/2026
0.5.4 59 11/17/2026
Loading failed