Entity Framework Core
Tayra integrates with Entity Framework Core through interceptors that transparently encrypt and decrypt [PersonalData] fields during SaveChanges and entity materialization. Beyond adding the interceptors to your DbContext, your queries, migrations and model configuration stay as they are.
Install
dotnet add package Tayra.EFCoreInstall-Package Tayra.EFCoreSupported EF Core Versions
One Tayra.EFCore package covers every supported EF Core line. It requires EF Core 8.0.0 or later and never moves your application to a newer EF Core than the one you reference.
| EF Core | .NET | Status |
|---|---|---|
| 8.0 | 8 and later | Supported, tested with every release |
| 9.0 | 8 and later | Supported, tested with every release |
| 10.0 | 10 and later | Supported, tested with every release |
| 11.0 | 11 and later | Release candidate: the full suite passes on 11.0 RC3; not yet part of every release run |
Every release runs the full EF Core suite (SQLite and PostgreSQL) against the newest patch of each line. The package has no upper bound, so a new EF Core major works the day it ships unless it changes the interceptor APIs Tayra uses.
Setup
EF Core only runs the interceptors a DbContext is configured with: it does not pick them up from your application's service container. Every DbContext that maps an entity with personal data must call UseTayra(), or that personal data is stored in cleartext.
DI-Based Setup (Recommended)
Register Tayra core services and the EF Core interceptors, then add the interceptors to the DbContext with UseTayra(sp):
var services = new ServiceCollection();
// Register Tayra core services and an in-memory key store
services.AddTayra(opts => opts.LicenseKey = licenseKey);
// Register Tayra EF Core interceptors via DI
services.AddTayraEFCore();
// Register the DbContext and add the interceptors with UseTayra(sp). EF Core does not pick
// interceptors up from the container on its own: without UseTayra(sp) nothing is encrypted.
services.AddDbContext<AppDbContext>((sp, opts) =>
opts.UseInMemoryDatabase("TayraSample")
.UseTayra(sp));
var provider = services.BuildServiceProvider();UseTayra(sp) works the same inside AddDbContextPool and AddDbContextFactory, and it reuses the same interceptor instances for every context.
Startup check
In a hosted application (anything built on IHost, such as ASP.NET Core or a worker service), AddTayraEFCore() checks every DbContext registered in the container when the application starts. If one maps an entity with personal data but has no Tayra interceptor, the start fails with an error naming the DbContext and the entity types. Set ValidateDbContextsOnStartup to false to turn the check off, for example for a DbContext that deliberately reads raw ciphertext.
Builder-Based Setup
If you prefer to pass ITayra directly, call UseTayra() on the DbContextOptionsBuilder:
// Alternative: pass the Tayra instance directly to UseTayra()
var tayra = provider.GetRequiredService<ITayra>();
var builderServices = new ServiceCollection();
builderServices.AddDbContext<AppDbContext>(opts =>
opts.UseInMemoryDatabase("TayraSampleBuilder")
.UseTayra(tayra, configure: efOpts =>
{
efOpts.EncryptOnSave = true;
efOpts.DecryptOnLoad = true;
}));UseTayra(tayra) creates its interceptors once per ITayra instance and reuses them, so calling it in an AddDbContext options action, which runs for every context, is safe.
When to Use Builder vs DI
Use the DI-based setup when you have a standard ASP.NET Core or hosted service application. Use the builder-based setup when you need fine-grained control or are configuring the DbContext outside of DI (e.g., in a migration tool or console app).
Options
// TayraEFCoreOptions - controls automatic encryption/decryption behavior
//
// Property Type Default Description
// ────────────── ────── ──────── ─────────────────────────────────────────
// EncryptOnSave bool true Encrypt [PersonalData] fields before SaveChanges
// DecryptOnLoad bool true Decrypt [PersonalData] fields after materialization
// ValidateDbContextsOnStartup bool true Fail a hosted app's start if a DbContext with
// personal data has no Tayra interceptor
services.AddTayraEFCore(opts =>
{
opts.EncryptOnSave = true; // Default: encrypt PII on SaveChanges
opts.DecryptOnLoad = true; // Default: decrypt PII on query materialization
opts.ValidateDbContextsOnStartup = true; // Default: refuse to start with an unprotected DbContext
});| Property | Type | Default | Description |
|---|---|---|---|
EncryptOnSave | bool | true | Encrypt [PersonalData] fields before SaveChanges |
DecryptOnLoad | bool | true | Decrypt [PersonalData] fields after entity materialization |
ValidateDbContextsOnStartup | bool | true | Fail a hosted application's start when a registered DbContext with personal data has no Tayra interceptor. Applies to AddTayraEFCore() only. |
Define Your Model
Annotate entity properties with [DataSubjectId] and [PersonalData] to enable automatic encryption:
public class CustomerEntity
{
public int Id { get; set; }
[DataSubjectId]
public string CustomerId { get; set; } = "";
[PersonalData]
public string Name { get; set; } = "";
[PersonalData(ReplacementValue = "redacted@example.com")]
public string Email { get; set; } = "";
/// <summary>
/// Not annotated - never encrypted by Tayra.
/// </summary>
public string AccountType { get; set; } = "";
}[DataSubjectId]onCustomerIdtells Tayra to derive the encryption key from this value.[PersonalData]onNameandEmailmarks them for encryption.- The
ReplacementValueparameter onEmailspecifies the value returned after crypto-shredding. AccountTypehas no attribute and is never touched by Tayra.
Every member shape Tayra supports works with EF Core: strings, nullable strings, string collections (EF Core primitive collections), and non-string values stored through a byte[] companion column. See Attributes.
DbContext
Your DbContext does not require any special configuration for Tayra. Define your DbSet<> properties and model configuration as usual:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<CustomerEntity> Customers => Set<CustomerEntity>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerEntity>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.CustomerId).IsRequired();
entity.Property(e => e.Name).IsRequired();
entity.Property(e => e.Email).IsRequired();
entity.Property(e => e.AccountType).IsRequired();
});
// In your DbContext.OnModelCreating, add a database index on the companion column
// so blind-index queries are efficient (avoids full table scans):
modelBuilder.Entity<ProtectedCustomer>()
.HasIndex(c => c.EmailHash);
}
}Column Sizes
Ciphertext is longer than the value it protects. A string column holds the base64 of the UTF-8 value plus 31 bytes, about 4 × (bytes + 31) / 3 characters, and more again with a masking prefix. A two-character value becomes 44 characters. Size personal data columns for the ciphertext, or leave them unbounded: a column sized for the cleartext makes the save fail on providers that enforce lengths, such as PostgreSQL and SQL Server.
Nested Personal Data
Personal data inside an owned type, an owned JSON column (ToJson()), or a complex type (ComplexProperty()) is encrypted with its owner's data subject key. Mark the navigation [DeepPersonalData]:
public class Shopper
{
public int Id { get; set; }
[DataSubjectId]
public string ShopperId { get; set; } = "";
[PersonalData]
public string Name { get; set; } = "";
// An owned type (or owned JSON column, or complex type) is encrypted with its owner's key.
// Mark the navigation [DeepPersonalData]: without it, SaveChanges refuses to store the
// owned type's personal data rather than storing it in cleartext.
[DeepPersonalData]
public PostalAddress Home { get; set; } = new();
}
public class PostalAddress
{
[PersonalData]
public string Street { get; set; } = "";
[PersonalData]
public string City { get; set; } = "";
public string Country { get; set; } = "";
}
public class ShopDbContext : DbContext
{
public ShopDbContext(DbContextOptions<ShopDbContext> options) : base(options)
{
}
public DbSet<Shopper> Shoppers => Set<Shopper>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
// OwnsOne(...).ToJson(), OwnsMany(...) and ComplexProperty(...) work the same way.
=> modelBuilder.Entity<Shopper>().OwnsOne(s => s.Home);
}When only the nested value changes, Tayra encrypts the owner along with it, so the change is never written in cleartext. An owned type with personal data that its owner does not mark [DeepPersonalData], and that has no [DataSubjectId] of its own, makes SaveChanges throw instead of storing it in cleartext.
A [BlindIndex] inside an owned type, complex type or owned JSON column is indexed too, and queried through the value object. See Value Objects.
How It Works
Tayra uses two EF Core interceptors to provide transparent encryption:
TayraSaveChangesInterceptor- Hooks intoSavingChanges. Before entities are persisted, it encrypts the[PersonalData]fields of every added or modified entity in the change tracker (and the owner of every added or modified owned entity). When the save ends, it puts each entity's plaintext back exactly as it was, so your application code keeps working with plaintext values, and records that plaintext as the entity's original values, so the change tracker sees the entity as unchanged and the nextSaveChangesdoes not rewrite it.The plaintext comes back however the save ends: success, failure, cancellation, or an optimistic concurrency conflict. After a failed save (a constraint violation, a concurrency conflict, a transient error) the tracked entities are plaintext again, so retrying, whether through an execution strategy such as
EnableRetryOnFailureor by callingSaveChangesagain, encrypts them once rather than twice.TayraMaterializationInterceptor- Hooks into EF Core's entity materialization pipeline. After EF Core creates an entity instance from a database row, it immediately decrypts any[PersonalData]fields before the entity is returned to your code. This covers tracking and no-tracking queries,Find,Include(single and split queries), explicit and lazy loading, andFromSql.
Performance Note
The materialization interceptor runs synchronously because the crypto engine caches keys in memory. After the initial key fetch from the key store, all subsequent encrypt/decrypt operations are memory-only lookups.
What Tayra Does Not See
Decryption happens when EF Core materializes an entity, and encryption when SaveChanges runs. Anything that bypasses one of those bypasses Tayra:
- Projections of personal data columns.
Select(c => c.Name), or a projection into a DTO, reads the column without materializing aCustomer, so it returns ciphertext. Project the whole entity (Select(c => c), or an anonymous type holding the entity) and map it to a DTO in memory. - Filtering on encrypted columns. Ciphertext is randomized, so
Where(c => c.Email == "jane@example.com")never matches. Use a blind index. - Bulk updates and raw SQL writes.
ExecuteUpdate,ExecuteDeleteandExecuteSqlnever reachSaveChanges, so a value set byExecuteUpdateis written in cleartext. Load the entities and save them instead. ReloadandGetDatabaseValues. These read the stored values without materializing an entity, so the entity is left holding ciphertext. UseReloadDecryptedAsync(below). If an entity reloaded withReloadis saved, Tayra recognizes the ciphertext and decrypts it before encrypting, so it is not encrypted twice.
Concurrency Conflicts
When SaveChanges throws DbUpdateConcurrencyException, the losing entity holds its plaintext again. To let the client win, take the database's concurrency token into the entity's original values and save again, as you would without Tayra. To let the database win, reload the entity with ReloadDecryptedAsync, which reloads and decrypts it:
// EF Core's Reload/ReloadAsync read the stored values without materializing an entity, so
// Tayra never sees them and the entity is left holding ciphertext. ReloadDecryptedAsync
// reloads and decrypts, leaving the entity unchanged.
await dbContext.Entry(customer).ReloadDecryptedAsync();Crypto-Shredding
GDPR Article 17 "right to be forgotten" is implemented via crypto-shredding. Instead of finding and deleting every row containing a person's data, you delete their encryption key. All encrypted data becomes permanently unreadable:
// GDPR "right to be forgotten" - delete the encryption key
var cryptoEngine = provider.GetRequiredService<ICryptoEngine>();
await db.ShredDataSubjectAsync(cryptoEngine, "cust-42");
Console.WriteLine("\n=== After Crypto-Shredding ===");
Console.WriteLine("All data for cust-42 is now permanently unreadable.");ShredDataSubjectAsync takes the subject's key id, including any [DataSubjectId(Prefix = ...)]. It deletes that key and every key under {keyId}: (rotated versions and key groups), the same as ITayra.ShredAsync. Another subject whose id merely starts with the same characters is not affected: shredding cust-1 leaves cust-12 intact.
After shredding, any subsequent query that materializes this customer's data will return replacement values instead of the original plaintext:
Namereturns""(the default replacement for strings)Emailreturns"redacted@example.com"(the custom replacement)
An entity already loaded into a long-lived DbContext keeps its plaintext after the shred, because EF Core returns the tracked instance for later queries in that context. Shred outside the request that holds the entity, or clear the change tracker after shredding.
Irreversible
Crypto-shredding is permanent. The encryption key is deleted from the key store and cannot be recovered. The original data is lost forever.
Data Migration
When adding Tayra to an existing application with pre-existing cleartext data, use the migration service to bulk-encrypt existing rows.
Register Migration Services
The migration encrypts each row itself, so it needs a DbContext over the same database without UseTayra(). A DbContext with Tayra's interceptor is refused, because it would encrypt every row twice.
// Register migration services (requires AddTayra() first)
var migrationServices = new ServiceCollection();
migrationServices.AddLogging();
migrationServices.AddTayra(opts => opts.LicenseKey = licenseKey);
migrationServices.AddTayraEFCoreMigrations();
var migrationProvider = migrationServices.BuildServiceProvider();
// The migration encrypts each row itself, so it needs a DbContext WITHOUT UseTayra() over the
// same database. A context with Tayra's interceptor is refused: it would encrypt every row twice.
var rawOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase("TayraMigration")
.Options;Encrypt Existing Data
The migration service scans entities in batches, in primary key order, detects cleartext vs. already-encrypted personal data, and encrypts only the cleartext rows. It inspects every kind of personal data member: strings, string collections, non-string members (through their companion column) and nested [DeepPersonalData] objects.
// Bulk-encrypt existing cleartext data in batches
var migrationService = migrationProvider.GetRequiredService<ITayraDataMigrationService>();
var result = await migrationService.EncryptExistingDataAsync<CustomerEntity>(
migrationDb,
batchSize: 50);
Console.WriteLine($"\n=== Migration Result ===");
Console.WriteLine($" Scanned: {result.TotalScanned}");
Console.WriteLine($" Encrypted: {result.Encrypted}");
Console.WriteLine($" Skipped: {result.Skipped}");
Console.WriteLine($" Errors: {result.Errors}");
Console.WriteLine($" Duration: {result.Duration.TotalMilliseconds:F0}ms");The MigrationResult includes:
TotalScanned- Total entities examinedEncrypted- Entities that were encrypted during this runSkipped- Entities that were already encryptedErrors- Entities with mixed encryption state (flagged for manual review)Duration- How long the migration took
Verify Encryption
After migration, verify that all rows contain valid Tayra wire format encryption. Each invalid row lists the member that holds cleartext, as a path such as Home.Street:
// Verify all rows are now properly encrypted
var verification = await migrationService.VerifyEncryptionAsync<CustomerEntity>(
migrationDb,
batchSize: 50);
Console.WriteLine($"\n=== Verification Result ===");
Console.WriteLine($" Verified: {verification.TotalVerified}");
Console.WriteLine($" Valid: {verification.Valid}");
Console.WriteLine($" Invalid: {verification.Invalid}");
Console.WriteLine($" Duration: {verification.Duration.TotalMilliseconds:F0}ms");
foreach (var invalid in verification.InvalidRows)
{
Console.WriteLine($" [INVALID] Entity {invalid.EntityId}, Property: {invalid.PropertyName} - {invalid.Reason}");
}Batch Size
Adjust batchSize based on your table size and available memory. The default is 100 rows per batch. For large tables, consider running migrations during off-peak hours.
See Also
- Getting Started - End-to-end encryption tutorial
- Attributes - All PII annotation attributes
- Blind Indexes - Searching encrypted columns
- Marten Integration - Document database integration
- Key Stores - Production key store options
