BccCode.Privacy.EntityFrameworkCore
0.27.1
dotnet add package BccCode.Privacy.EntityFrameworkCore --version 0.27.1
NuGet\Install-Package BccCode.Privacy.EntityFrameworkCore -Version 0.27.1
<PackageReference Include="BccCode.Privacy.EntityFrameworkCore" Version="0.27.1" />
<PackageVersion Include="BccCode.Privacy.EntityFrameworkCore" Version="0.27.1" />
<PackageReference Include="BccCode.Privacy.EntityFrameworkCore" />
paket add BccCode.Privacy.EntityFrameworkCore --version 0.27.1
#r "nuget: BccCode.Privacy.EntityFrameworkCore, 0.27.1"
#:package BccCode.Privacy.EntityFrameworkCore@0.27.1
#addin nuget:?package=BccCode.Privacy.EntityFrameworkCore&version=0.27.1
#tool nuget:?package=BccCode.Privacy.EntityFrameworkCore&version=0.27.1
BccCode.Privacy.EntityFrameworkCore
Changes in 0.14. The final design (design, plan) replaces parts of this API:
UsePrivacy(),CaseKey, dated groups,IncludeRetained, moments,BeginErasure, row-level security andPrivacyGrants.GrantApplicationAsyncare replaced byAddPrivacy<TContext>(), data classes, the per-process projection and guards, the job SDK (IPrivacyJobs) andPrivacyDatabase.GrantRuntimeAccessAsync. This README is rewritten with the code (plan steps 12–21).
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 outsidePrivacyMaintenance. Each personal entity has two named filters: the organisation (readership) filter, never relaxed, and its own retention filter (PrivacyRetention:<type>), whichIncludeRetained()relaxes on its own root only; every other root in the query keeps both. Any otherIgnoreQueryFilterson a shareable entity is refused (outside erasure, below). For a retained row's history, take its ids from the same query and read the versions withIgnoreQueryFilters()(F16). - Erasure (a retention job):
PrivacyMaintenance.BeginErasure(db, reason)selects the scope organisation's rows that privacy hides (no basis covers them any more, such as a lapsed member's) so the job can delete them with their dependents. Until it is disposed, every root and everyIncludeof the context sees the organisation's rows whatever their processes; the organisation filter stays, so other organisations' rows are never read. It is maintenance too (saves are not limited to the process), and each use is logged with its reason. Run it on a context of its own: the scope's other contexts see the hidden rows while it runs. With ChangeHistory, erase inside the same block with itsEraseByIdAsync(ids, q => q.Include(...))(0.4.70), which also erases the rows' history and returns aMaintenanceResultwith the erased count per table. Its maintenance queries useIgnoreQueryFilters: insideBeginErasure(only), anIgnoreQueryFilterson a personal entity is admitted as "every filter except the organisation filter", so it still reads the scope organisation's rows only. Outside erasure it is refused as before, also when EF reuses the query shape compiled during erasure. Use a fresh context forEraseByIdAsync(no event intent, no tracked rows), and map the relationships it erases withOnDelete(DeleteBehavior.Restrict): ChangeHistory erases dependents through the include, never by cascade.using (PrivacyMaintenance.BeginErasure(db, "retention: members lapsed over two years")) { var profiles = await db.PersonProfiles.Include(p => p.Addresses).Where(p => lapsed.Contains(p.PersonId)).ToListAsync(); var memberships = await db.Memberships.Where(m => lapsed.Contains(m.PersonId)).ToListAsync(); db.RemoveRange(profiles.SelectMany(p => p.Addresses)); db.RemoveRange(profiles); db.RemoveRange(memberships); await db.SaveChangesAsync(); } - A failing moment is rolled back, logged and counted (
bcc.privacy.moments.failed);ApplyDueAsyncapplies 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).
Adoptions (LIB-14)
The application's own data decides which organisations a process applies to: an organisation set up, a module turned on. Tell the package in the transaction of that business event; it derives the group bases and (with the outbox, LIB-5) sends the adoption to Privacy. There is no local adoption list and no adoption check per request: processing is gated by bases only, and without an adoption there is no basis. A process adopted automatically at first login needs nothing from the application.
// the application's set-up event (source "app"); ValidTo ends it
await db.RecordAsync(new AdoptionRecord { Organisation = org, ProcessSlug = Slugs.Register, Process = 1,
Values = new Dictionary<string, string> { ["retention"] = """{"period":2,"unit":"Years"}""" }, Groups = ["members"] });
await db.SaveChangesAsync();
Privacy stores each organisation's variable values (owner's decision): the application reads them from Privacy, or
keeps the ones it uses (such as retention) in its own data; the package stores none.
modelBuilder.UsePrivacySyncGuard() turns on the synchronisation-path guard: consent bases (Kind = "consent") are
then written only inside PrivacySync.Begin(reason), as the consent projection writes them; an ordinary save that
writes one is refused.
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.4.70
(the version BccCode.Privacy.ChangeHistory is built on; 0.4.43 to 0.4.63 are partial releases) depends on EF Core
Relational 10.0.15 and the same provider 10.0.3, so both packages resolve one EF Core version with no pin in the
application. Pin EF Core in the application only if it uses a newer patch than 10.0.15.
Keeping Privacy in step (opt-in, LIB-5)
modelBuilder.UsePrivacySync() adds privacy.outbox and privacy.consent. Then, in the transaction of the change:
an adoption recorded with RecordAsync is queued for Privacy (contract c1). Per-person bases are not sent yet: Privacy
has no endpoint for them (c1 proposes PUT /api/bases/{process}/{org}/{person}), so the package offers no API for them
until it does; the application never writes a basis to Core. services.AddPrivacyOutbox<TContext>() registers the
dispatcher, which needs an IPrivacySyncTransport (Privacy) and optionally an ICoreGroupTransport (group members the
application owns, milestone 3). Hosting's app.MapPrivacySync<TContext>() maps POST /internal/privacy/outbox,
/reconcile and /backfill for a scheduler (both read the application's current adoptions from its own data through an IPrivacyAppAdoptions it registers); nothing is sent at start-up or on a request. Only the newest message per key
is sent; a failure stays pending and is retried; each message carries a source version, so a delayed retry never
overwrites a newer state. db.ApplyAsync(ConsentEvent) applies Privacy's consent, restriction and objection events to the
consent projection, one transaction each, ignoring older events; AllowsAsync reads it.
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; BeginErasure also selects the organisation's hidden rows for deletion |
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) |
Bypasses
Some EF calls go around the privacy layer: its query filters, its projection and its guards. They are allowed, not
banned. The package ships an analyzer (in analyzers/dotnet/cs, active as soon as you reference
BccCode.Privacy.EntityFrameworkCore) that marks each one, so every bypass in the code base is visible and explained.
| Diagnostic | Raised on |
|---|---|
PRIVACY200 (warning): "'…' bypasses privacy checks" |
FromSql, FromSqlRaw, FromSqlInterpolated; Database.SqlQuery, SqlQueryRaw, ExecuteSql, ExecuteSqlRaw, ExecuteSqlInterpolated and their Async forms; IgnoreQueryFilters; EF.CompileQuery and EF.CompileAsyncQuery (a compiled delegate skips the query guard after its first compile); Database.GetDbConnection (a raw connection) |
PRIVACY201 (warning): "PRIVACY200 is suppressed without a reason" |
#pragma warning disable PRIVACY200 without a comment on the same line, or [SuppressMessage(…, "PRIVACY200", …)] without a Justification |
Suppress a bypass with the reason it is safe:
#pragma warning disable PRIVACY200 // Counts rows for a health metric; returns no personal data.
var count = await db.Database.SqlQueryRaw<int>("select count(*) as \"Value\" from app.application").SingleAsync();
#pragma warning restore PRIVACY200
[SuppressMessage("Privacy", "PRIVACY200", Justification = "Maintenance: deletes rows no process may read.")]
static Task<int> Purge(AppDbContext db) => db.Database.ExecuteSqlRawAsync("delete from app.application where allowed_processes = '{}'");
Through normal EF LINQ the privacy layer holds; a bypass shows up as a suppressed warning with its reason. There is no
database-level enforcement: anyone who can run SQL as the application can read the tables. ExecuteUpdate and
ExecuteDelete are not bypasses: they go through the query guard and the row filter.
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).
The process adapter (0.14 preview, beside the runtime above)
The adapter for the new declarations (data classes and processes, LIB-23) is registered next to AddDbContext:
services.AddDbContext<ATeamDbContext>(o => o.UseNpgsql(connectionString));
services.AddPrivacy<ATeamDbContext>(PrivacyModels.FromAssemblies(typeof(ApplicationData).Assembly));
services.AddPrivacyChangeHistory(); // with ChangeHistory: privacy columns unversioned, the org owns the events
- The model. Each personal entity gets
allowed_processes,person_link(not on child entities) andlast_reduced_at, check constraints and a comment on every column naming its category. The package tables and the catalogue (as seed data) are in the model too, so a normaldotnet ef migrations addholds everything. - Reads. A query filter keeps the rows of the request's orgs whose
allowed_processeshold its process. The host sets the scopedPrivacyContext(Use(orgs, slug)); without it a context sees no personal rows. - Writes. Saving derives
allowed_processesas the privacy job does (PrivacyKeeps:where:, a basis that covers the person, the period, restrictions and objections), and refuses a row of another org. See Keeps and bases below.allowed_processesandperson_linkare concurrency tokens, so a stale write after a reduction fails. - A second context.
IPrivacyContextFactory<TContext>.ForProcess<T>()for another process, andForSystem(reason)for maintenance: no filter, the reason required and logged with every save. - No pooling.
AddDbContextPoolandAddPooledDbContextFactoryare refused (atAddPrivacy, or when the first context is created): a context finds itsPrivacyContextthrough the request scope. UseAddDbContextorAddDbContextFactory. - Statement preparation.
AddPrivacyaddsMax Auto Prepare=20to the connection string unless it sets it: the privacy filters make longer statements, which plan faster prepared.
Core API groups and their criteria
A data-subject group can be a Core API group. Its criteria list the Core Person fields that the group's filter may use,
as a lambda over the Core API SDK's Person (BccCode.Core.Api.Client.Model.Person):
using Person = BccCode.Core.Api.Client.Model.Person;
PersonalDataCategories<ReferenceData>()
.DataSubjects("reference-persons", criteria: (Person p) => new { p.RoleAssignments })
.LegalBasis(Article6.LegitimateInterest, justification: "…");
- Fields only. List members,
p => p.ChurchUidorp => new { p.RoleAssignments, p.Address.City }; anything else isPRIVACY022. The core package stays free of the SDK:DataSubjects<TPerson>takes any type. - Field paths. Hosting turns the criteria into Core API field paths (
roleAssignments,address.city), the names in the SDK's model, which are the ones BccCode.Linq puts in a Core filter:PrivacyCoreCriteria.FieldPaths(group).PrivacyCoreCriteria.Validate(model)reportsPRIVACY022for criteria that are not fields of the SDK'sPerson. Publish and the start-up checks (with the new Hosting, LIB-23) run it, and adoptions' group filters are checked against these paths (LIB-14).
Sharing between orgs (LIB-27, Core API's model)
- Tables.
privacy.legal_baseswithlegal_basis_data_sources,privacy.group_legal_baseswithgroup_legal_basis_groups, andprivacy.group_members. Every data source names the personal data categories it gives. - Writes, with the domain change.
db.SetLegalBasisAsync(new LegalBasisWrite { … }),RemoveLegalBasisAsync,SetGroupLegalBasisAsyncandRemoveGroupLegalBasisAsyncstage the change;SaveChangesAsyncwrites it in the same transaction. A second write with the same receiver, person (or groups), process and reference changes the basis and raises its version; a removal ends it and keeps it as history. Only the receiver or a source org may write. DisclosedTo..DisclosedTo<ApplicationData>(data => [data.Profile], to: (Application a) => a.ChurchUid)on a process keeps a person basis in step with the column on every save.- Reads.
privacy.effective_data_sourcesis what each receiver may read now (person bases, plus group bases bounded to their members, categories and excluded source orgs).visible.<table>holds the reader's own rows that its process keeps and the other orgs' rows it receives, with only the received categories' columns, markedis_shared; each row appears once; it reads the reader from the session settingsbcc_privacy.orgsandbcc_privacy.process. Read it from EF withdb.Visible<T>()ordb.ReadVisibleAsync<T>(q => …)(untracked), which call its functionvisible.<table>_rows(orgs, process)with the reader as parameters, so no session setting is left on a pooled connection. - Release records (opt-in):
AddPrivacy<TContext>(models, o => o.RecordReleases()).ReadVisibleAsyncthen writes oneprivacy.release_recordper response that holds other orgs' rows;Visible<T>()is refused.
Consents, restrictions and objections (LIB-5)
AddPrivacy registers PrivacyConsentHandler<TContext>, which applies Privacy's events once each, through the system
context. Events are ordered by their own timestamp per org, process and person; an older event or a repeat is ignored.
Hosting maps one endpoint per event with app.MapPrivacyConsentEvents<AppDbContext>(): POST /internal/privacy/events/{consent-given|consent-withdrawn|restriction-set|restriction-lifted|objection-upheld}. Configure
the required privacy-events policy to authorize the trusted push subscriber. To use another policy, pass the route prefix
and policy name to the mapping call. Each application needs its subscription to Privacy's events (scopes
privacy.consents#read and privacy.restrictions#read), set up at adoption.
- Consent.
consent-givenis stored inprivacy.consentsand writes a person legal basis (privacy_referenceconsent) with the consented categories. A later grant replaces changed categories and a withdrawal ends the basis. Apply an EF migration to add the nullableprivacy.consents.process_revisioncolumn before upgrading a subscriber. It holds the event's revision ID, and the existing numeric revision remains available for older readers. - Restriction (Art. 18).
restriction-set, of kindrestrictionorobjection(an objection while it is assessed), takes its process offallowed_processesof the person's rows, so the process no longer sees them, and the job pauses their reduction (PrivacyRestrictions.RestrictedSql).restriction-liftedrestores both. - Upheld objection (Art. 21).
objection-upheldends the person's legitimate-interest bases for that process and keeps it off their rows. One to a statistics process (21(6)) is also queued as an erasure request inprivacy.outbox.
Keeps and bases: stage the basis with the save
A save keeps a process in a row only while a basis covers the row's person: a consent, a legal basis the application
writes (for the person, or for a group: a group legal basis covers the group's current members), or membership of the
process's data-subject group (processes without data-subject groups cover everyone). The
privacy job (BccCode.Privacy.Jobs) uses the same evaluation, so a save never widens a row the job reduced.
Stage the basis with the save. Call db.SetLegalBasisAsync(…) before the same SaveChangesAsync that adds the row,
so the basis is written in the same transaction and counts for the row. For a consent process, request consent at login
(RequestConsentAtLogin<TProcess>()), so the consent exists before the first save. Otherwise the row is not kept by
that process (it does not see the row) until the basis exists; a row added under that process's context then logs a
warning naming the process and the entity, "no basis yet".
When a save writes person legal bases (SetLegalBasisAsync, RemoveLegalBasisAsync), group legal bases
(SetGroupLegalBasisAsync, RemoveGroupLegalBasisAsync) or group members (ReplaceCoreGroupMembersAsync, rows of a
DataSubjects<TRow> group), the rows of the persons concerned (for a group basis, its groups' members) are derived again
at once, set-based (PrivacyRederivation.ForPersonsAsync), so a row saved before its basis carries the process without
being saved again; child entities follow at their next save or the job's next run. A member whose until passes, or
who is removed outside a save, drops out at the row's next save or the job's next run.
Fields a process does not keep
A context serves one process (Use(orgs, processId): the slug, or slug/key for a sub-process, which sees only its
own categories). Its queries return the fields of the personal data categories that process keeps; every other field
comes back blank: null, an empty collection, or the data class's BlankWith value. This holds for plain columns, owned
types, complex types and JSON documents, through public EF hooks only:
- Entities. A materialization interceptor blanks the fields as each entity is created. For a tracked query the
original values are blanked too, so the entity is not seen as changed and a save never writes the blanks. Complex
types stored as JSON are set after the entity is created: a tracked query blanks them when the entity is tracked, a
query that does not track them gets them blanked by a final
Selectthe adapter adds. - Projections. A query's final
Selectthat reads a category field (a => new { a.FirstName, a.Address.Street },EF.Property, or items of a JSON list) reads it through the entity, so it is blanked the same way. The rewrite depends only on the declarations, never on a process, so one cached query plan serves every process: the check is made when the query runs. - Saves. A save refuses a value in a field the process does not keep, and, under a
.Pseudonymised()process, a write of the data subject. Columns the process does not keep are never written, since they are not changed. - JSON documents with hidden fields (decision 4). When a save rewrites a JSON document in which the process does
not keep every field,
privacy.merge_unheldputs the hidden fields back from the stored document, in the same transaction: list items are matched by their stable key, an item the process removed is removed whole, and a new item has none. A list whose items a process keeps only some fields of needs a stable key (a property namedId, or one marked[Key]); start-up refuses one without (PRIVACY023). The stable key is not personal data: it needs no map, and the privacy job never blanks it. Every other field the job blanks must be blankable, including a field inside an object whose category another category maps into (PRIVACY004). - Bulk statements.
ExecuteUpdatemay not write or read a column holding a category the process does not keep, nor write the data subject under a pseudonymised process; it is checked when it runs.ExecuteDeleteremoves whole rows the process sees, as a tracked delete does.
Known limits.
- Hidden values are still read from the database and blanked in the application, unless the projection does not select them.
Where,OrderBy,GroupByand aggregates on a hidden field use the stored value in SQL. Avoid them under a process that does not keep the field.- A list of a JSON document whose items the process keeps none of is put back whole by a save; the process cannot remove its items.
Compiled models and precompiled queries
Both are allowed, with a warning. With a compiled model (UseModel, as dbcontext optimize generates) rows are still
filtered by org and process, since the named query filter is in the model, and entities are still blanked on
materialization. What does not apply: the start-up checks of the privacy model (they run while EF builds the model),
and, for a precompiled query (EF.CompileQuery, or one precompiled at build), the projection rewrite above, which runs
when EF compiles a query. The adapter logs a warning when a compiled model is used, and the analyzer warns on
EF.CompileQuery (PRIVACY200).
The runtime above is removed before 0.14.0.
| Product | Versions 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. |
-
net10.0
- BccCode.Privacy (>= 0.27.1)
- BccCode.Privacy.Postgres (>= 0.27.1)
- BccCode.Privacy.Vocabulary (>= 1.0.20)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.15)
- Microsoft.Extensions.Caching.Memory (>= 10.0.15)
- Microsoft.Extensions.Compliance.Abstractions (>= 10.11.1)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 10.0.4)
NuGet packages (3)
Showing the top 3 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. |
|
|
BccCode.Privacy.Jobs
The privacy job of BCC Privacy: works out what each process keeps in each row, blanks the categories no process keeps, pseudonymises the person when no process needs them identified, erases rows nothing keeps, and answers erasure requests. Runs through the EF Core adapter's job context. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.27.1 | 0 | 11/24/2026 |
| 0.27.0 | 0 | 11/24/2026 |
| 0.26.0 | 0 | 11/24/2026 |
| 0.25.1 | 0 | 11/24/2026 |
| 0.25.0 | 10 | 11/24/2026 |
| 0.24.0 | 10 | 11/24/2026 |
| 0.23.6 | 12 | 11/24/2026 |
| 0.23.5 | 11 | 11/24/2026 |
| 0.23.4 | 10 | 11/24/2026 |
| 0.23.3 | 53 | 11/24/2026 |
| 0.23.2 | 60 | 11/24/2026 |
| 0.23.1 | 52 | 11/24/2026 |
| 0.23.0 | 53 | 11/24/2026 |
| 0.22.0 | 57 | 11/24/2026 |
| 0.21.0 | 72 | 11/23/2026 |
| 0.20.0 | 54 | 11/23/2026 |
| 0.19.0 | 60 | 11/23/2026 |
| 0.18.0 | 61 | 11/23/2026 |
| 0.17.0 | 59 | 11/23/2026 |
| 0.16.0 | 62 | 11/23/2026 |