BccCode.Privacy.EntityFrameworkCore 12.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package BccCode.Privacy.EntityFrameworkCore --version 12.0.0
                    
NuGet\Install-Package BccCode.Privacy.EntityFrameworkCore -Version 12.0.0
                    
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="12.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BccCode.Privacy.EntityFrameworkCore" Version="12.0.0" />
                    
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 12.0.0
                    
#r "nuget: BccCode.Privacy.EntityFrameworkCore, 12.0.0"
                    
#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@12.0.0
                    
#: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=12.0.0
                    
Install as a Cake Addin
#tool nuget:?package=BccCode.Privacy.EntityFrameworkCore&version=12.0.0
                    
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: data classes (PrivacyData<T>), processes and sub-processes (PrivacyProcess), their checks, [PrivacyProcess<T>] and the PrivacyContext of a unit of work. No framework dependency
BccCode.Privacy.Postgres The PostgreSQL schema the declarations make: the privacy columns, package tables and catalogue
BccCode.Privacy.EntityFrameworkCore This package: the privacy layer in an ordinary EF Core model, its filters by org and process, the derivation on save, hiding, sharing, consents and the read audit
BccCode.Privacy.Jobs The privacy job: retention, blanking, pseudonymising and erasure (IPrivacyJobs)
BccCode.Privacy.AspNetCore The PrivacyContext per request from the org claim and the endpoint's [PrivacyProcess<T>]; consent at sign-in
BccCode.Privacy.Wolverine The org, process and person on message envelopes, and the PrivacyContext before every handler
BccCode.Privacy.ChangeHistory ChangeHistory on the same model: events and history read per org, the privacy columns unversioned
BccCode.Privacy.Hosting The one AddPrivacy<TContext>() wiring the above; defaults per environment; the declarations checked at start-up against the revision the deploy accepted, and published by privacy publish; the adopted values read from Privacy. 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.

Purpose-bound access to personal data in EF Core and PostgreSQL. A row is returned only to the orgs of the work and only while a process they work for keeps it; the developer API stays ordinary EF: the same DbContext, DbSet, LINQ and SaveChangesAsync. Design: docs/architecture-proposal/final. Version 0.x: the API will change. Licence: Apache 2.0. It targets .NET 10 (LTS), EF Core 10 and Npgsql's EF Core 10 provider, on PostgreSQL 18, as BccCode.ChangeHistory does.

Use

An application declares its personal data as data classes and its processes as classes, and registers privacy for its context once, with Hosting:

builder.Services.AddDbContext<ATeamDbContext>(o => o.UseNpgsql(connectionString));   // an ordinary DbContext
builder.Services.AddPrivacy<ATeamDbContext>(o => o.Declare(typeof(ApplicationData).Assembly));

app.UseAuthentication();
app.UsePrivacy();
app.MapGet("/applications", [PrivacyProcess<ParticipationProcess>] (ATeamDbContext db) => db.Applications.ToListAsync());

Without Hosting (a library, a test), this package alone registers the EF layer:

services.AddDbContext<ATeamDbContext>(o => o.UseNpgsql(connectionString));
services.AddPrivacyEntityFrameworkCore<ATeamDbContext>(PrivacyModels.FromAssemblies(typeof(ApplicationData).Assembly));
services.AddPrivacyChangeHistory();   // with ChangeHistory: privacy columns unversioned, the org owns the events

With ChangeHistory, AddPrivacyChangeHistory() also turns on FilterEventsByOrganisation() and FilterHistoryByCurrentRow(): a reader sees an event only when all its links belong to its org, and a history version only while the current row passes the privacy filter. A child entity's events belong to its parent's org, through the navigation to the parent; a child moved to another parent is then visible only to the new parent's org.

  • The model. Each personal entity gets allowed_processes, person_link (not on child entities) and last_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 normal dotnet ef migrations add holds everything.
  • Reads. A query filter keeps the rows of the request's orgs whose allowed_processes hold its process. Use [PrivacyProcess<TProcess>] on an ASP.NET Core action, minimal API handler or Wolverine message handler. Enable the privacy middleware with services.AddPrivacyAspNetCore() and app.UsePrivacy() for HTTP, or opts.UsePrivacy() for Wolverine handlers. The middleware supplies the acting org, and the EF adapter fixes the context to the declared process or sub-process, on first use. An endpoint, a handler or a Wolverine middleware can set the scoped PrivacyContext itself with Use(orgs, processId) before that; the entry point's then does not apply. A context without an org and process sees no personal rows. allowed_processes holds process ids: a process's slug, or slug/key for a sub-process. A row only a sub-process keeps is that sub-process's, not its parent's: a parent's where: hides it from the parent even while the sub-process keeps it. A sub-process context sees the rows it keeps and those its parent keeps.
  • One PrivacyContext per scope. Each context the container creates gets the PrivacyContext of the scope that created it, also when its options are a singleton (ChangeHistory's AddChangeHistory<T> registers them so). Register the context (AddDbContext or AddChangeHistory) before AddPrivacy, so the adapter can wrap its registration. PrivacyContext has no public constructor: the container makes it, so Wolverine takes the scope's one for a handler or middleware parameter instead of making its own.
  • Writes. Saving derives allowed_processes as the privacy job does (PrivacyKeeps: where:, a rule that covers the person, the period, restrictions and objections), and refuses a row of another org. See Keeps below. allowed_processes and person_link are concurrency tokens, so a stale write after a reduction fails.
  • A second context. IPrivacyContextFactory<TContext>.ForProcess<T>() for another process, and ForSystem(reason) for maintenance: no filter, the reason required and logged with every save.
  • No pooling. AddDbContextPool and AddPooledDbContextFactory are refused (at registration, or when the first context is created): a context finds its PrivacyContext through the request scope. Use AddDbContext or AddDbContextFactory.
  • Statement preparation. The adapter adds Max Auto Prepare=20 to 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.ChurchUid or p => new { p.RoleAssignments, p.Address.City }; anything else is PRIVACY022. 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) reports PRIVACY022 for criteria that are not fields of the SDK's Person. Publish and the start-up checks run it.

Adoptions: Privacy owns them

Code declares who may adopt a process, AdoptableBy(org, ...) (none: only the data controller); it is published in the process document. Privacy owns every adoption and all its values: it adopts the process for its org at publish when AdoptableBy names exactly one (a single-controller application), and people adopt and set values (the groups' members, the variables) in Privacy's UI or the portal. The libraries never write adoptions; they read them (PrivacyAdoptedValues, see Hosting).

An adoption picks a group's members under populations.<group>: Core groups by uid (groupUids) or a Core filter (groupFilter).

  • Core-group adoption requires criteria. Only a group declared with criteria: takes Core groups or a filter; a filter may read only the fields its criteria list, and fields inside them (the items of roleAssignments). The application checks the values as it reads them and logs anything else as a warning: Privacy owns the values, so it cannot stop start-up over them, and such values cover no one (the loader fills only criteria groups), so the application fails closed. Privacy has the criteria in the process document to refuse them when they are set.

Sharing between orgs: disclosure rules

Processing permissions are rules in code. There are no per-person or per-group permission rows: who a process covers follows from consents, group membership and the application's own rows (see Keeps below), and what another org may read follows from disclosure rules.

  • Disclosure rules (org to org). .Discloses<ApplicationData>(data => [data.WorkPart, data.ThirdParties], to: Orgs.WnT, forProcess: "wnt-job-applications") on a process discloses those categories of every row it keeps to the recipient org's process, which reads them under its own legal basis. The rule is declared in code and seeded as a catalogue row in privacy.disclosure_rules by the normal EF migration (or the script), so removing it from code ends it with the next migration. A rule may name child data (InterviewData under ApplicationData): child rows follow their parent's org and person.
  • The discloser's basis. The discloser owns the disclosure's legal basis: basis: on Discloses (Art. 6), with specialCategoryException: (Art. 9(2)) and withinTheBody: (9(2)(d)). Without basis: the rule rests on consent: the person allows the disclosure on the receiver's consent screen, Privacy sends it with the receiver's consent-changed event (dataSharing, one entry per source org), and the handler keeps it in privacy.data_sharing_consents. A row is then disclosed only while that person allows it for this receiving process and source org, and only the categories they allow. With basis: (for example basis: Article6.LegitimateInterest) the rule needs no consent. PRIVACY020 refuses a special category on a basis other than consent without specialCategoryException:, and Art. 9(2)(d) without withinTheBody: true. The receiver reads under its own basis, which is its own accountability (SaaS terms §5.4, independent legal basis): a receiving process on consent needs the person's own consent to it (privacy.consents); any other receiving basis is taken as given. The per-person group check for the receiver follows with coverage.
  • A recipient named by the row. to: may be an org column of the row instead of a fixed org: .Discloses<ProfileData>(data => [data.Name], to: (Profile p) => p.ChurchUid, forProcess: "church-members"). Each row is disclosed to the org its column names, while it names it; a row whose column is null is disclosed to no one. The column must be a Guid or Guid? property of the entity itself (PRIVACY020 otherwise), stored in its own column.
  • The catalogue row. privacy.disclosure_rules uses Core's names: controller_org_uid (the fixed recipient; NULL when the row names it), controller_org_column (the quoted column that names it; NULL for a fixed org), process_slug (the recipient process), personal_data_categories, source_process, table_name, condition_sql and condition_text, legal_basis (NULL: consent), special_category_exception and within_the_body. There is no source org: it is each row's own org. A database with the earlier columns (recipient_org_uid, recipient_process) gets the table re-created by the script and reseeded; EF users get it through their next migration.
  • Checks. PRIVACY020 refuses a rule without a recipient, with a to: that is not an org column of the entity, a recipient process that is not a slug, a category the process does not keep, or data without an org and data subject of its own or its parent's, and the special-category cases above. privacy check lists the rules with their basis, and the revision includes them. Sending them to Privacy's Art. 30 record follows once the client contract has a field for recipients.
  • Rule conditions. A rule may add where: (Application a) => a.Status == "accepted", so it discloses only the rows that match. The condition may read only the entity's own scalar columns, constants and DateTime.UtcNow, joined with &&, || and !; it becomes plain SQL (now() for the time). Captured variables, adopted values, method calls, navigations, fields inside a JSON column and enums are refused at start-up (PRIVACY024), so the grant never depends on state the catalogue cannot see. The catalogue row keeps the SQL in condition_sql and the C# text in condition_text, and each rule has a numeric id; the visible.* functions grant a rule's categories only for rows where its condition holds.
  • Reads. visible.<table> holds the reader's own rows that its process keeps and the other orgs' rows a rule grants it (rows the rule's source process keeps, that match its condition, whose recipient is one of the reader's orgs), with only the granted categories' columns (the others NULL, or their BlankWith value), marked is_shared; each row appears once, with the union of the categories of the rules that grant it. It reads the reader from the session settings bcc_privacy.orgs and bcc_privacy.process. Read it from EF with db.Visible<T>() (untracked, normal LINQ), which calls its function visible.<table>_rows(orgs, process) with the reader as parameters, so no session setting is left on a pooled connection. A received row's allowed_processes reads ~received, not the source org's processes; EF keeps its received categories as the database returns them, also when the reader's process keeps none of them on its own rows. Under a process declared .AuditEveryRead(), a Visible<T>() read is logged in privacy.read_audit like any other read: one row per table and source org (the received rows under their own org), with the data subjects. A direct SQL read of visible.* is not logged.
  • Upgrading. The script, and EF's next migration, drop privacy.legal_bases, legal_basis_data_sources, group_legal_bases, group_legal_basis_groups, release_record and the view privacy.effective_data_sources. SetLegalBasisAsync, RemoveLegalBasisAsync, SetGroupLegalBasisAsync, RemoveGroupLegalBasisAsync, DisclosedTo, ReadVisibleAsync and RecordReleases() are gone: declare a DataSubjects<TRow> group over a table of your own for exceptions, DataSubjects(name, criteria:) for Core API groups, and Discloses(…, to: row => row.OrgColumn, …) for a recipient named by the row.

Consents, restrictions and objections (LIB-5)

The adapter registers PrivacyConsentHandler<TContext>, which applies Privacy's events once each, through the system context. Events are ordered by their own timestamp per consent or restriction record; an older event or a repeat is ignored. Hosting maps one endpoint per event with app.MapPrivacyConsentEvents<AppDbContext>(): POST /internal/privacy/events/{consent-changed|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. A consent is stored once, in privacy.consents: one row per org, process and person, with given, changed_at, the granted categories and the process revision. There is no person legal basis for it. A process whose legal basis is Article6.Consent keeps a person's rows while that row is given (PrivacyConsents.GivenSql gives the rule as SQL; a pseudonymised row matches through privacy.pseudonym). consent-changed (the client's PrivacyConsentChanged) sets it: Given = true with the granted categories replacing the earlier ones, or Given = false on a withdrawal, which keeps the row so its changed_at orders later events. Privacy's older consent-withdrawn event is not subscribed. Either re-derives the person's rows at once. The granted categories are recorded; they do not narrow what the org's own process keeps. Apply an EF migration to add the nullable privacy.consents.process_revision column 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 kind restriction or objection (an objection while it is assessed), takes its process off allowed_processes of the person's rows, so the process no longer sees them, and the job pauses their reduction (PrivacyRestrictions.RestrictedSql). restriction-lifted releases that restriction and both resume once the last restriction for the process has ended. Before upgrading an existing subscriber, scaffold an EF migration for the changed restriction key and use migrationBuilder.Sql(PrivacySql.PackageTables) in place of the scaffolded changes to privacy.restrictions. The package SQL preserves existing restriction records.
  • Upheld objection (Art. 21). objection-upheld is recorded in privacy.restrictions and keeps a legitimate-interest process off the person's rows. It also ends the temporary pause from that objection. One to a statistics process (21(6)) is also queued as an erasure request in privacy.outbox.

Keeps: what covers a person

A save keeps a process in a row only while a rule covers the row's person. A process without data-subject groups covers everyone its declaration selects. Otherwise one of its groups covers the person:

  • by consent: a given consent in privacy.consents, for a group whose legal basis is consent (DataSubjects(name) on a consent process);
  • by membership of a Core API group: privacy.group_members, for DataSubjects(name, criteria:). The table is the one cache of Core's memberships, one row per (Core group, person, org, process, declared group): a member covers only the process whose adoption names that Core group for the group, never another process of the org that declares a group of the same name. Hosting's built-in loader fills it from the Core groups the adoptions name, at start-up and by the nightly core-groups job (Core groups); its one write is db.ReplaceCoreGroupMembersAsync(org, process, name, groupUid, members), which a member without a start starts at the application's TimeProvider now;
  • by the application's own rows: DataSubjects<TRow>(name, person: r => r.PersonUid, until: r => r.Until, org: r => r.OrgUid). This is a rule over the table TRow, with no copy anywhere: a row covers the person it names (or the org's pseudonym of them) for the rows of its org while its until: has not passed. A DateOnly until: covers through that day (UTC); a DateTime or DateTimeOffset until: is exclusive. The row's org is org:, else the Org its data class maps, else (a TRow with neither) the application's single org; an application that acts for several orgs must name it (PRIVACY026). person:, org: and until: each read one column of the row, and until: is in no personal data category, since a blanked end would cover with no end (PRIVACY027). A person-specific exception (a dispute, a legal claim) is a small table of the application's own, such as Dispute { Id, OrgUid, PersonUid, Until }. The cover reads the table itself, past the query filters and whatever the context's process hides.

A group declared with DataSubjects(name) (no criteria, no row type) on a basis other than consent could be covered by nothing, so the checks refuse it (PRIVACY025). The privacy job (BccCode.Privacy.Jobs) uses the same evaluation, so a save never widens a row the job reduced.

Cover the person before or with the save. Request consent at login (AddAuthentication().RequestConsentAtLogin<TProcess>(), ASP.NET Core package), so the consent exists before the first save, or save the row of the application's own group (the dispute) with the domain row: a row of a group's table staged in a save counts for that save. Otherwise the row is not kept by that process (it does not see the row) until something covers the person; 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 consents (privacy.consents, as the consent handler does), Core group members (ReplaceCoreGroupMembersAsync) or rows of a DataSubjects<TRow> group's table (added, changed or removed: the persons named before and after), the rows of the persons concerned are derived again at once, set-based (PrivacyRederivation.ForPersonsAsync), so a row saved before its coverage carries the process without being saved again; child entities follow at their next save or the job's next run. A cover that ends on its own (an until: that passes, a Core member's ValidTo) or a member removed outside a save drops out at the row's next save or the job's next run, which derives every row again.

  • Consent on first need, for the data subject. Under a process whose legal basis (or its parent's) is consent, a save that adds or changes a row whose data subject is the signed-in person (PrivacyContext.PersonUid, set from the request or the message), such as an applicant starting their own application, checks privacy.consents for that person and the context's one org (PrivacyConsents.GivenSql). Without a given consent nothing is written and PrivacyConsentRequiredException (process and org, never the person) is thrown; the ASP.NET Core middleware asks for it (see that package). Staff saving other persons' rows, and reads, are never asked. A context without a person, with several orgs, or for maintenance is not checked.
  • Read audit. A process declared .AuditEveryRead() (or under such a parent) logs every personal row it reads in privacy.read_audit: one row per query, table and org, with the time, process, user, row count and the data subjects (person_uids), never a value of the row; reads of other orgs' rows through Visible<T>() too, under their source org. Not logged, as with the other bypasses (PRIVACY200): raw SQL, maintenance reads, and reads still pending on a connection the application opened itself (Database.GetDbConnection) and EF never closes. Add an EF migration for the new privacy.read_audit.person_uids column (or run PrivacySql.PackageTables).

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 Select the adapter adds.
  • Projections. A query's final Select that 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_unheld puts 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 named Id, 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. ExecuteUpdate may 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. ExecuteDelete removes whole rows the process sees, as a tracked delete does.
  • The person under a pseudonymised process. Under a .Pseudonymised() process an entity's data subject reads as the org's pseudonym of that person (privacy.pseudonym), in entity queries, tracked queries and projections (a => a.PersonUid reads through the entity, as above); a row the job already pseudonymised holds the pseudonym itself. The context loads its orgs' pseudonyms once, on the connection of its first query, so there is no query per row. The pseudonym is also the original value of a tracked entity, so a save never writes it back. The job creates the pseudonym of each person whose identified rows a pseudonymised process keeps ({Entity}.PseudonymCreated); until it has, that person reads as blank (Guid.Empty, or null).

Known limits.

  • Hidden values are still read from the database and blanked in the application, unless the projection does not select them.
  • Where, OrderBy, GroupBy and aggregates on a hidden field use the stored value in SQL. Avoid them under a process that does not keep the field. The same holds for the person under a pseudonymised process: group by the person in the application, after the query, or return DTOs without raw ids.
  • 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.

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.

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 tests' model is the A-team sample (BccCode.Privacy.Tests/Sample); each test creates its schema from the model.

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 adapter, the privacy context of each request, consent at sign-in, the privacy job and its endpoints, the Core group loader, the declarations checked at start-up, and the application's processes published to the Privacy API at deploy. Wolverine and ChangeHistory are optional packages: o.UseWolverine(), o.UseChangeHistory().

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
14.6.8 45 11/26/2026
14.6.7 42 11/26/2026
14.6.6 44 11/26/2026
14.6.5 47 11/26/2026
14.6.4 46 11/26/2026
14.6.3 53 11/26/2026
14.6.2 45 11/26/2026
14.6.1 51 11/26/2026
14.6.0 42 11/26/2026
14.5.0 49 11/26/2026
14.4.0 45 11/26/2026
14.3.0 42 11/26/2026
14.2.0 43 11/26/2026
14.1.1 43 11/26/2026
14.1.0 50 11/26/2026
14.0.1 46 11/26/2026
14.0.0 48 11/26/2026
13.0.0 49 11/26/2026
12.0.1 38 11/26/2026
12.0.0 47 11/26/2026
Loading failed