Csharpessentials efcore

From senrecep/CSharpEssentials · View interactive version

Csharpessentials efcore is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when wiring EF Core with CSharpEssentials domain models. Covers AuditInterceptor/DomainEventInterceptor/SlowQueryInterceptor registered via DI, BaseDbContext (InterceptorsFromServices, DispatchDomainEventsOnSaveChanges), PaginateAsync/Paginate, KeysetPaginateAsync (composite keyset pagination wi

How to use this skill

Skill file

CSharpEssentials.EntityFrameworkCore

EF Core interceptors, a base DbContext, pagination, soft delete and Result-returning queries that integrate with EntityBase and domain events.

Installation

dotnet add package CSharpEssentials.EntityFrameworkCore

Targets net10.0 (EF Core 10), net9.0 (EF Core 9) and net8.0 (EF Core 8). There is no net11.0 target.

Namespaces

using CSharpEssentials.EntityFrameworkCore;                       // BaseDbContext, DbContextInterceptors, SoftDeleteAsync, *AsResultAsync
using CSharpEssentials.EntityFrameworkCore.Interceptors;          // interceptors, IAuditUserIdProvider, IDomainEventPublisher, ISlowQueryHandler
using CSharpEssentials.EntityFrameworkCore.Pagination;            // PaginateAsync, Paginate, KeysetPaginateAsync
using CSharpEssentials.EntityFrameworkCore.Pagination.Requests;   // PaginationRequest, KeysetPaginationRequest
using CSharpEssentials.EntityFrameworkCore.Pagination.Responses;  // PaginationResponse<T>, KeysetPaginationResponse<T>
using CSharpEssentials.EntityFrameworkCore.Pagination.Keyset;     // KeysetOrdering<T>, KeysetPaginationOptions, ICursorProtector, KeysetCursorErrors
using CSharpEssentials.EntityFrameworkCore.Extensions;            // AddCqrsDbContexts, AddWriteDbContext, AddReadDbContext

Interceptors

Register the interceptors in DI, then attach them to the context:

builder.Services.AddAuditInterceptor(sp =>
    sp.GetRequiredService<IHttpContextAccessor>().HttpContext?.User.Identity?.Name ?? "system");
builder.Services.AddSlowQueryInterceptor(TimeSpan.FromMilliseconds(500));
builder.Services.AddSingleton<DomainEventInterceptor>();
builder.Services.AddScoped<IDomainEventPublisher, MediatorDomainEventPublisher>();

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
    options.UseSqlite("Data Source=app.db")
           .AddInterceptors(
               sp.GetRequiredService<AuditInterceptor>(),
               sp.GetRequiredService<DomainEventInterceptor>(),
               sp.GetRequiredService<SlowQueryInterceptor>()));

AuditInterceptor

During SaveChanges it stamps CreatedAt/CreatedBy on added ICreationAudit entries and UpdatedAt/UpdatedBy on modified IModificationAudit entries, and turns the delete of an ISoftDeletable (not marked with MarkAsHardDeleted()) into a soft delete. The soft delete also keeps the tracked entries EF cascade-deleted with it: owned types stay, ISoftDeletable dependents are soft-deleted, other Cascade/ClientCascade dependents go back to Unchanged. AddAuditInterceptor registers the interceptor, a scoped IAuditUserIdProvider from your factory, and TimeProvider.System unless a TimeProvider is already registered. AddAuditUserIdProvider registers only the provider. Implement the interface yourself for anything more complex:

public class HttpAuditUserIdProvider(IHttpContextAccessor accessor) : IAuditUserIdProvider
{
    public string GetCurrentUserId() =>
        accessor.HttpContext?.User.Identity?.Name ?? "system";
}

DomainEventInterceptor

Publishes IDomainEvents raised on entities through IDomainEventPublisher (or IDomainEventOutbox for after-save events, when registered):

public class MediatorDomainEventPublisher(ILogger<MediatorDomainEventPublisher> logger) : IDomainEventPublisher
{
    public Task PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)
    {
        logger.LogInformation("Publishing {Event}", domainEvent.GetType().Name);
        return Task.CompletedTask;
    }
}

SlowQueryInterceptor

Logs commands slower than SlowQueryOptions.Threshold (default 1 second) as warnings. Parameter values appear only with EnableSensitiveDataLogging(); otherwise each reads @name=?. Register an optional ISlowQueryHandler for metrics or alerts; an exception it throws is logged and the command still succeeds:

public class SlowQueryMetrics(ILogger<SlowQueryMetrics> logger) : ISlowQueryHandler
{
    public void OnSlowQuery(SlowQueryContext context) =>
        logger.LogWarning("Slow query ({Elapsed} ms): {Sql}", context.ElapsedTime.TotalMilliseconds, context.CommandText);
}

BaseDbContext

Opt-in interceptor attachment from DI and domain event dispatch around SaveChanges:

public sealed class AppDbContext(DbContextOptions<AppDbContext> options, IServiceScopeFactory scopeFactory)
    : BaseDbContext<AppDbContext>(options, scopeFactory)
{
    protected override DbContextInterceptors InterceptorsFromServices =>
        DbContextInterceptors.Audit | DbContextInterceptors.SlowQuery;

    protected override bool DispatchDomainEventsOnSaveChanges => true;
}

Enum storage

ConfigureEnumConventions stores [StringEnum] enums by wire name (same spelling as JSON) and adds a check constraint ck_{table}_{column}_enum per column. Enums without [StringEnum] keep EF's integer default.

public class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
{
    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
        configurationBuilder.ConfigureEnumConventions(EnumConventions.Default);
        // Existing database with integer enum columns: keep them, first migration stays empty
        // configurationBuilder.ConfigureEnumConventions(EnumConventions.Default, existingStorage: EnumStoredAs.Integer);
}

modelBuilder.Entity<Order>().Property(o => o.Status).HasEnumStorage(EnumStorage.String);              // per property
modelBuilder.Entity<Order>().Property(o => o.Kind).HasLegacyEnumStorage(EnumStoredAs.MemberName);     // keep old text format
modelBuilder.Entity<Order>().Property(o => o.Priority).HasEnumCheckConstraint(false);                 // no constraint

Maybe columns

EF Core cannot make a non-nullable struct property optional, so Maybe<T> always maps to NOT NULL. Declare Maybe<T>? to store absence as NULL:

public sealed class Customer
{
    public int Id { get; set; }
    public Maybe<int>? LoyaltyPoints { get; set; }   // INTEGER NULL
    public Maybe<string>? Nickname { get; set; }     // TEXT NULL
}

configurationBuilder.ConfigureNullableMaybeConventions();                                   // all Maybe<T>? properties
modelBuilder.Entity<Customer>().Property(c => c.LoyaltyPoints).HasNullableMaybeConversion(); // or per property

Maybe<int> points = customer.LoyaltyPoints.Flatten();   // null becomes None (CSharpEssentials.Maybe)

Pagination

// Offset-based
PaginationResponse<Order> page = await db.Orders
    .OrderByDescending(o => o.CreatedAt)
    .PaginateAsync(pageNumber: 1, pageSize: 20, cancellationToken: ct);

IReadOnlyList<Order> items = page.Items;
int total = page.TotalCount;   // -1 when includeTotalCount: false
bool more = page.HasNextPage;  // also PageNumber, PageSize, TotalPages, HasPreviousPage

// Request object with optional search
var request = new PaginationRequest { PageNumber = 2, PageSize = 10, Search = "pen" };
PaginationResponse<Product> products = await db.Products
    .PaginateAsync(request, search: term => p => p.Name.Contains(term), cancellationToken: ct);

The single-column cursor PaginateAsync(cursorRequest, cursorSelector, ...) is [Obsolete] since 6.0; use KeysetPaginateAsync below with a unique key (add the id as a tie-breaker).

Paginate is the synchronous variant and also works on in-memory IQueryable<T>. Offset pagination caps PageSize at PaginationDefaults.MaxPageSize (100) by default: IPaginationRequest.Normalize() lowers larger values to 100, and PaginateAsync/Paginate take an optional maxPageSize (pass int.MaxValue to turn the cap off; cap < 1 throws ArgumentOutOfRangeException).

Keyset (composite cursor) pagination

Prefer this for feeds and APIs. One query reads limit + 1 rows, no COUNT, opaque cursors for both directions:

Result<KeysetPaginationResponse<Order>> page = await db.Orders
    .Where(o => o.CustomerId == customerId)
    .KeysetPaginateAsync(
        new KeysetPaginationRequest { Limit = 20, After = after, Before = before }, // never both
        k => k.Descending(o => o.CreatedAt).Descending(o => o.Id),                // end with a unique key
        ct);
// page.Value.Items, NextCursor (send as After), PreviousCursor (send as Before), HasNext, HasPrevious

// Options: max limit (default 100), max cursor length (default 2048), cursor protection, custom predicate
var options = new KeysetPaginationOptions { MaxLimit = 50, Protector = myDataProtectionWrapper };

Soft delete and Result queries

// One UPDATE statement; bypasses the change tracker and SaveChanges interceptors
int affected = await db.Set<Article>()
    .Where(a => a.Title.StartsWith("draft"))
    .SoftDeleteAsync(deletedBy: "admin", cancellationToken: ct);

// Result-returning queries: Error.NotFound() (or your error) instead of null
Result<Order> order = await db.Orders.Where(o => o.Total > 100).FirstOrDefaultAsResultAsync(cancellationToken: ct);
Result<Order> byKey = await db.Orders.FindAsResultAsync([orderId], cancellationToken: ct);
Result saved = await db.SaveChangesAsResultAsync(ct);

Add a global filter for soft-deleted rows with modelBuilder.ApplySoftDeleteQueryFilter() in OnModelCreating.

On net10.0 (EF Core 10) use named filters instead, so a query can drop soft delete and keep the others (never mix them with the anonymous ApplySoftDeleteQueryFilter; EF Core rejects both on one entity):

modelBuilder.Entity<Order>()
    .HasSoftDeleteQueryFilter()                                            // named QueryFilterNames.SoftDelete
    .HasQueryFilter(QueryFilterNames.Tenant, o => o.TenantId == tenantId);
// or modelBuilder.ApplyNamedSoftDeleteQueryFilter() at the end of OnModelCreating

List<Order> withDeleted = await db.Orders.IgnoreSoftDeleteQueryFilter().ToListAsync(ct); // Tenant filter still applies

Migrating from the anonymous ApplySoftDeleteQueryFilter(): named keys do not switch off an anonymous filter, so IgnoreSoftDeleteQueryFilter() ignores nothing until the model uses ApplyNamedSoftDeleteQueryFilter()/HasSoftDeleteQueryFilter(). Change the model first, then the queries. The helpers throw when the entity already has an anonymous filter, skip owned types, and only filter root types (a soft-deletable type under a non-soft-deletable root gets no filter). Pass filter keys in a static readonly string[] or new[] { ... }, never a collection expression or List: EF Core 10.0.x recompiles the query for those.

Analyzer CSE3001 (Info by default; raise with dotnet_diagnostic.CSE3001.severity = warning in .editorconfig) flags parameterless IgnoreQueryFilters() when EF Core 10 is referenced; the code fix rewrites it to IgnoreQueryFilters(new[] { QueryFilterNames.SoftDelete }) for ISoftDeletableBase entities and requires the named filter in the model.


Entity mapping and Result helpers

public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>   // Order : SoftDeletableEntityBase<Guid>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.SoftDeletableEntityBaseGuidIdMap();   // key, audit columns (user columns max 40), IsDeleted/DeletedAt/DeletedBy; IsHardDeleted is ignored
        builder.OptimisticConcurrencyVersionMap();    // shadow byte[] "RowVersion" row version
        builder.Property(o => o.Metadata).HasJsonConversion(columnType: "jsonb");
    }
}
// EntityBaseGuidIdMap() for an EntityBase<Guid>; EntityBaseMap<TEntity, TId>(userIdMaxLength: 64) for any key type

Result<Order> one = await db.Orders.SingleOrDefaultAsResultAsync(cancellationToken: ct);   // Error.NotFound() when no row
db.HardDelete(entity);                        // MarkAsHardDeleted + Remove (the AuditInterceptor keeps the delete)
await db.MigrateDataAsync<Country, CountrySeed>(seed, (set, data) => set.Any(), s => new Country { Code = s.Code }, ct);

ApplySoftDeleteQueryFilter() adds an anonymous !IsDeleted filter to every root ISoftDeletableBase type; AddQueryFilter<T>(expression) ANDs your filter with the existing anonymous one. MigrateDataAsync also has an overload with MigrateDataOptions<TEntity, TSeed, TKey> for a key-based add/update/remove diff. ISqlConnectionFactory and ISqlReadOnlyConnectionFactory are interfaces for Dapper-style code; you implement and register them.


Database error translation

DbErrorTranslation turns persistence exceptions into Error values (the AspNetCore package renders them as ProblemDetails). The built-in SqlStateErrorTranslator reads DbException.SqlState:

| SQLSTATE | Error | Code |

|---|---|---|

| 23505 | Conflict | Database.UniqueViolation |

| 23503 | Conflict | Database.ForeignKeyViolation |

| 23514 | Validation | Database.CheckViolation |

| 23502 | Validation | Database.NotNullViolation |

| 40001 | Conflict, retryable: true | Database.SerializationFailure |

| 40P01 | Conflict, retryable: true | Database.Deadlock |

using CSharpEssentials.EntityFrameworkCore.DbErrors;

builder.Services.AddDbErrorTranslation();
builder.Services.AddDbErrorTranslator<MyProviderTranslator>();   // optional IDbErrorTranslator, runs before the SQLSTATE default

Result<int> saved = await translation.SaveChangesAsync(db, ct);   // translated error, or rethrows an unrecognized exception
bool known = translation.TryTranslate(exception, out Error error);

The metadata carries sqlState and, when there are entries, entities; the database message is not copied. Translators must be stateless (DbErrorTranslation is a singleton). SaveChangesAsResultAsync is different: it turns every exception into an Unknown error, except cancellation of your token.


Transaction runner

using CSharpEssentials.EntityFrameworkCore.Transactions;   // AddEfCoreTransactionRunner
using CSharpEssentials.Transactions;                       // ITransactionRunner (CSharpEssentials.Core)

builder.Services.AddEfCoreTransactionRunner<AppDbContext>();   // scoped ITransactionRunner

Result result = await runner.ExecuteAsync(
    ct => orders.PlaceAsync(command, ct),     // returns ValueTask<Result>
    outcome => outcome.IsSuccess,             // commit or roll back
    cancellationToken);

The outermost call runs inside CreateExecutionStrategy() with a transaction, so retrying strategies work (a retry re-runs the whole unit on a cleared change tracker; the context must have no pending changes at the start). A nested call on the same context instance joins the transaction, behind a savepoint when the provider supports them. It needs a relational provider (the InMemory provider throws on BeginTransactionAsync) and does not combine with an ambient TransactionScope.


Idempotency records

using CSharpEssentials.EntityFrameworkCore.Idempotency;   // AddIdempotencyRecords, EfCoreIdempotencyRecordStore<TContext>

protected override void OnModelCreating(ModelBuilder modelBuilder) =>
    modelBuilder.AddIdempotencyRecords(Database.ProviderName);   // then add a migration

builder.Services.AddEfCoreTransactionRunner<AppDbContext>();
builder.Services.AddMediatorTransactionRunnerBehavior();
builder.Services.AddMediatorIdempotencyBehavior(o => o.Placement = IdempotencyPlacement.InsideTransaction);
builder.Services.AddEfCoreIdempotencyRecordStore<AppDbContext>();            // default store
builder.Services.AddEfCoreIdempotencyRecordStore<AppDbContext>("payments");  // or: keyed store for profiles with StoreKey = "payments"

Records are written with SQL inside the context's current transaction, so a rolled-back request leaves no record and its retry runs again; a concurrent duplicate waits for the first commit and replays its response. The primary key is KeyHash, a binary(32) SHA-256 of the storage key, so keys that differ in case or trailing spaces stay separate under any collation; the readable Namespace/Scope/Key columns get the provider's binary collation (KeyCollation overrides it, e.g. utf8mb4_nopad_bin on MariaDB), which only makes them case-sensitive: SQL Server ignores trailing spaces under every collation, _BIN2 included, so only the KeyHash key separates them there (on PostgreSQL never turn the columns into char(n), which pads). Needs READ COMMITTED. In Observe mode the executor and the HTTP middleware reserve and release through store.Detached (own context and connection) and write a result to store through the store itself, in the business transaction, so a failed commit leaves no record and is not replayed after the switch to Enforce; a failed result write rolls back to a savepoint and the business data commits without the record (on PostgreSQL always so under an isolation level stricter than READ COMMITTED; on SQL Server a transaction doomed by XACT_ABORT ON or a SNAPSHOT update conflict, error 3960, is lost with the business data, because a savepoint cannot save it). Expired rows count as absent; call PurgeExpiredAsync from a hosted service to delete them.


Enum column migrations

migrationBuilder.ConvertEnumColumn<OrderStatus>("orders", "Status", from: EnumStoredAs.Integer, to: EnumStorage.String);
migrationBuilder.ConvertEnumJsonPath<OrderStatus>("orders", "payload", ["status"]);   // PostgreSQL jsonb
string sql = EnumDataAudit.Sql<OrderStatus>("orders", "Status", storedAs: EnumStoredAs.Integer, provider: db.Database.ProviderName);

When you drop HasLegacyEnumStorage/existingStorage for a column, replace the generated AlterColumn with ConvertEnumColumn (analyzer CSE0014 reports a forgotten one) and keep the check-constraint operations around it. EnumDataAudit.Sql returns a read-only query that lists the stored values the conversion or constraint would reject, with their counts; run it before deploying. SQL is generated for PostgreSQL and SQLite only.


CQRS registration

builder.Services.AddCqrsDbContexts<WriteDbContext, ReadDbContext>(
    configureWrite: (sp, options) => options.UseSqlite("Data Source=app.db"));

The write context is pooled with change tracking; the read context is pooled with NoTracking. AddWriteDbContext<T> and AddReadDbContext<T> register them one at a time. AddPooledDbContext<T> and RegisterDbContextFactory<T> register a pooled context and an IDbContextFactory<T>. Every registration method has an overload that takes Action<DbContextRegistrationOptions> first (EnableDetailedErrors, EnableSensitiveDataLogging, QueryTrackingBehavior, and EnableAuditInterceptor/EnableDomainEventInterceptor/EnableSlowQueryInterceptor, which attach the interceptor only when it is registered in DI). MigrationsAssembly, RetryOptions and QuerySplittingBehavior on that class are not applied by this version; set them in the provider callback. UseAsWriteContext(), UseAsReadContext() and UseAsReadContextWithIdentityResolution() are available on DbContextOptionsBuilder.


Best practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.