Attritect: Design

Status: Draft v0.2, 2026-11-24 Scope: a .NET 10 rewrite of the author’s earlier attribute-driven CRUD engine (ASP.NET MVC 5 / EF 5 / AngularJS)


1. Goal

Keep the idea that made the earlier engine work:

Describe a model with attributes, and you get a complete CRUD page: list, search, add/edit, validation, permissions and persistence, with no controller code and no view per page.

Fix what held it back: in-memory querying, security gaps, a dead stack, hard-coded language and calendar, and the fact that it was never separated from the app it lived in.

Two audiences, in this order:

  1. The author’s own projects. It must be fast to adopt and easy to override.
  2. Other developers, as an open-core library with paid pro packages (§14). So no commercial dependencies, a clean package split, docs, and stable public APIs.

Non-goals (v1)

  • A visual designer or low-code UI. Pages stay defined in C#.
  • Generating database schema. The engine works on top of an existing EF Core model (code-first or database-first, §6.4).
  • Replacing hand-written screens. Complex workflows keep custom pages and use the engine for the simple 80%.
  • A UI in the free packages. They ship the API and the JSON page schema; renderers are pro (§11).

2. At a glance

Earlier engine (one page took 3 things: model, empty controller, mapper registration):

public class NationalityModel : GenericModel
{
    public NationalityModel() { SetPublicSettings("Nationality", "Nationalities", links, ...); }

    [GridViewShown(true, "Code")] public int ID { get; set; }

    [GridViewShown(true)] [Required] [String100] [Contains] [DisplayField("Name")]
    [Remote("CheckDuplicate", "Nationality", AdditionalFields = "ID")]
    public string Name { get; set; }
}
public class NationalityController : ViewGridBaseController<NationalityModel> { }
// + mapper registration in both directions

Attritect (one page is one class, nothing else):

[CrudPage("nationalities", Entity = typeof(Nationality), Title = "Nationalities")]
public class NationalityModel
{
    [Key, Grid(Title = "Code", Sortable = true)]
    public int Id { get; set; }

    [Grid(Sortable = true), Search(Op.Contains), Field]
    [Required, SafeText(100), Unique]
    public string Name { get; set; } = "";
}
// Program.cs: once per app (implemented in phase 1)
builder.Services
    .AddCrudEngine(o => o.AddPagesFrom(typeof(NationalityModel).Assembly))
    .UseEntityFrameworkCore<AppDbContext>()
    .AddHttpApi();                       // generic controllers, routes, ProblemDetails

app.MapCrudEngine();                     // HTTP API + page schema under /api/crud (replaces MapControllers)

The registration methods live in the Microsoft.Extensions.DependencyInjection / Microsoft.AspNetCore.Builder namespaces (standard .NET convention), so they need no extra using. Multi-tenancy (§9) is added in phase 2.

Scanning rule: AddPagesFrom scans top-level types (public or internal) and public nested types. Private nested types are ignored, which keeps test doubles and helpers out of discovery.

You don’t write a controller, a view or a mapping. To override anything, you opt in (§7, §8).


3. Naming and packages

3.1 The product name is changeable

“Attritect” is the working name. It appears only in:

  • package IDs and assembly names, derived from one MSBuild property in Directory.Build.props:
    <EngineName>Attritect</EngineName>
    <AssemblyName>$(EngineName).$(MSBuildProjectName)</AssemblyName>
    <RootNamespace>$(AssemblyName)</RootNamespace>
    <PackageId>$(AssemblyName)</PackageId>
    
  • C# namespaces (namespace Attritect.Core;)

Everything a user touches is name-neutral: attributes (CrudPage, Grid, Field, …), DI and endpoint methods (AddCrudEngine, MapCrudEngine), interfaces (ICrudService<T>, ICrudStore), routes (/api/crud) and policy names (crud:{permission}:{action}).

Project folders are named by role (src/Core/Core.csproj), not by product. A scripts/rename.ps1 changes EngineName and rewrites namespaces in one step. A rename costs users only their using lines.

3.2 Packages

Package (Attritect.*) Depends on Contents License
Abstractions BCL + DataAnnotations only Attributes, enums, PageSchema model, and extension interfaces: ICrudHooks<T>, IQueryCustomizer<T>, ICrudPermissionProvider, ITenantResolver. Page models need only this package. MIT
Core Abstractions (no EF Core, no ASP.NET Core) Metadata, query engine, mapping, tenant isolation, and the overridable base classes CrudService<TModel,TEntity>, CrudQueryBuilder<,>, PageMapper<,>, PageSchemaBuilder (§7.1). Framework-free, so an app’s Application layer may reference it to subclass services (§13.2). MIT
EntityFrameworkCore Core, EF Core 10 ICrudStore implementation: entity resolution, queries, save/delete, unique checks, soft delete and tenant query filters MIT
AspNetCore Core Generic controllers, routing, authorization, schema endpoint, ProblemDetails errors MIT
Analyzers (phase 5) — Roslyn analyzers + source generator: compile-time checks, reflection-free accessors MIT
Pro.* packages (§14) free packages UI renderers, audit & history, import/export, database-per-tenant. Activated by an offline license key. Live in a separate private repo. Commercial

Target framework: net10.0 (LTS until Nov 2028). Add the next LTS (.NET 12) when it ships.

Dependency rule: no commercial or copyleft dependencies in MIT packages. That rules out AutoMapper (commercial since 2025) and MediatR. Mapping is built in (§6).


4. Attributes

4.1 Class level

[CrudPage(
    "nationalities",                  // route key / page id (required, unique)
    Entity      = typeof(Nationality),// EF entity; explicit, no mapper-list scanning
    Title       = "Nationalities",    // or a resource key (§10)
    ItemTitle   = "Nationality",      // singular, for "Add Nationality"
    Group       = "Settings",         // menu grouping / breadcrumb parent
    Permission  = "lookups",          // policy prefix (default: page id)
    Tenancy     = TenantScope.Auto,   // Auto | Tenant | Shared (§9)
    DefaultSort = "Name")]

4.2 Property level

Attribute Replaces (earlier engine) Meaning
[Key] (DataAnnotations) UniqueColumn = "ID" Identity of the row
[Grid(Title, Order, Sortable, Format, Width)] [GridViewShown] Column in the list
[Field(Label, Type, Order, Placeholder)] [DisplayField] Field on the add/edit form. Only [Field] properties are writable (stops overposting).
[Search(Op.Contains)], [Search(Op.Between)], … [Contains], [Equals], [Between], [GreaterThan], [DateEquals], [SearchNameShown] Searchable with that operator. It appears in the schema’s search section automatically.
[Filter(value)] [Const(value)] Fixed filter, always applied. Several on one property are ORed; different properties are ANDed.
[Unique] [Remote("CheckDuplicate", …)] + controller action Unique within the table (and tenant), excluding the current id. Remote-check endpoint provided and enforced again on save.
[Computed] mapper ForMember setups Read-only, filled from an expression (§6.2)
[Lookup(typeof(CityModel))] + ICrudLookups LookupManger<T>.GetSelectListItem(...) (reflection-invoked) Foreign key chosen from another page (§4.4). The text shown comes from that page’s LookupText.
[Parent(typeof(PackageModel))] DefaultProgram?PackageId=... links + hand-written filters Makes the page a child (detail) page of another (§4.4)
[Required], [StringLength], [Range], [EmailAddress], [RegularExpression] custom duplicates of each Standard DataAnnotations work as-is
[SafeText(max)], [Phone(Region.SA)], [NationalId(Region.SA)] 50+ classes (String6…String1000, SafeString15…) A few parameterized presets
[Audit] on class [LogName] Include in the audit log (pro, §14)

Op values: Eq, NotEq, Contains, StartsWith, Gt, Gte, Lt, Lte, Between, In, IsNull. Values are converted to the property’s real type (int, decimal, DateOnly, enum, bool, Guid), not compared as strings.

4.3 Row actions

[RowAction("report", Label = "Report", Icon = "chart", Navigate = "/reports/packages/{id}", EnabledBy = "canReport")]

Edit and Delete exist by default and depend on permissions. Per-row enablement comes from a [Computed] bool CanDelete / CanEdit, computed in SQL. Child pages add their own row action automatically (child:{page}, navigating to the child list filtered by the row). Actions are data in the schema (§11), not HTML.

4.4 Lookups and master-detail (implemented in phase 3)

[CrudPage("package-courses", Entity = typeof(PackageCourse))]
public class PackageCourseModel
{
    public int Id { get; set; }

    [Parent(typeof(PackageModel)), Field]          // detail of a package
    public int PackageId { get; set; }

    [Lookup(typeof(CourseModel)), Field, Required] // chosen from the courses page
    public int CourseId { get; set; }

    [Grid] public string? CourseName { get; set; } // flattened: Course.Name, in SQL
}

Lookups

  • Options come from the referenced page: GET /api/crud/courses/lookup?q=mat&take=20 (search), or ?ids=3&ids=7 (labels for existing values). The result is a list of { value, text }. The text is the page’s LookupText (default: a Name or Title property, else the first text column).
  • Tenant-safe: options and save-time validation both run as the caller, with tenant scope and fixed filters. A key pointing to another tenant’s row is rejected with 400, exactly like a key that doesn’t exist.
  • Lookup and parent keys are filterable with equality automatically (f.courseId=3).
  • Startup checks: the referenced page exists, the key types match, and the lookup page has text to show.

Lookup helper for app code (ICrudLookups, the successor of the earlier LookupManger<T>)

public class ReportsController(ICrudLookups lookups) : Controller
{
    public async Task<IActionResult> Index(int? cityId, CancellationToken ct)
    {
        var cities   = await lookups.GetAsync<CityModel>(ct);                    // all options (small tables)
        var some     = await lookups.GetAsync<CityModel>("ri", take: 20, ct);    // autocomplete
        var label    = await lookups.GetTextAsync<CityModel>(42, ct);            // text for one stored value
        var any      = await lookups.FromEntityAsync<Country, int>(c => c.Id, c => c.Name, ct); // a table that isn't a page
        ViewBag.Cities = cities.ToSelectList(selected: cityId, placeholder: "Choose...");     // MVC / Razor
        return View();
    }
}
  • Same rules as the endpoint: tenant scope and fixed filters apply. FromEntityAsync filters by the tenant property by convention (plus shared rows when it’s nullable). There’s no permission check, because this is server-side code, like the old helper.
  • Lookups have their own limit, o.MaxLookupItems (default 1,000), separate from list paging, so small tables load completely.
  • [Lookup(typeof(NationalityModel), Preload = true)] embeds all options in the page schema (fields[].lookup.options), only when the caller may view the lookup page. Use it for small tables; large ones keep using the search endpoint.
  • ToSelectList() lives in the ASP.NET Core package, in the Microsoft.AspNetCore.Mvc.Rendering namespace, so Core stays free of MVC.

Master-detail

  • Listing a child page needs the parent: f.packageId=…, otherwise 400 (RequiredForList = false turns this off).
  • The parent must be visible to the caller (tenant-safe), and can’t change on update (400).
  • The parent page’s schema lists its children, and each child adds a child:{page} row action. The child’s schema names its parent.
  • A [Parent] key must also be a [Field], so new rows can be given their parent (startup check).
  • Deleting a parent that still has children is refused by the database (409). Show it per row with a computed CanDelete.

5. Query engine (the biggest fix)

Earlier problem: filter lambdas used d.GetType().GetProperty(..).GetValue(..), and the repository took a compiled Func<>. Every list, search and count therefore loaded the whole table into memory.

New rule: everything stays IQueryable<TEntity> and becomes SQL.

Pipeline for GET /api/crud/{page}?page=2&size=20&sort=name:asc&f.name=ali&f.cityId=3:

  1. Resolve page → cached PageMetadata (built once at startup, stored in a FrozenDictionary).
  2. Bind filters. Only keys declared with [Search] are accepted. Unknown keys are ignored, and the value is parsed to the property type (a bad value returns 400 with a field error).
  3. Build the predicate from real expression trees: Expression.Property(param, "Name") + string.Contains (EF translates it to LIKE), typed constants for equality and ranges, combined with AndAlso/OrElse. (The earlier engine used bitwise And/Or + Expression.Invoke, which EF can’t translate.)
  4. Fixed filters ([Filter]) are added the same way. Tenant and soft-delete filters come from EF Core named global query filters (§9), so they can’t be bypassed by forgetting a line.
  5. Sort. Only Sortable columns are allowed. Multi-column sort works, with a stable tie-break on the key.
  6. Project to the model in SQL (§6.1), so only the needed columns are selected.
  7. Page. CountAsync and Skip/Take + ToListAsync, both async. Maximum page size is configurable (default 100).

Text and case: by default, text comparisons follow the database collation (SQL Server is usually case-insensitive; SQLite and PostgreSQL are case-sensitive). Two levels, the most specific wins:

  • Per property: [Search(Op.Contains, Case = TextCase.Insensitive)] or Case = TextCase.Sensitive.
  • Engine-wide: o.CaseInsensitiveText = true for every property left at TextCase.Default.

Ignoring case lower-cases both sides, so the database can’t use an index for that comparison. Use it where it matters (names), not everywhere. The schema reports a property’s explicit setting (ignoreCase) to renderers. The same setting applies to [Unique] checks on that property.

Test guarantee: every operator has a unit test that calls ToQueryString() on SQLite and SQL Server providers to prove it translates to SQL. A query that falls back to client evaluation fails the build.

Escape hatches: subclass CrudQueryBuilder<TModel, TEntity> and override one step (ApplySearch, ApplyFixedFilters, ApplySort, ApplyPaging; see §7.1). Or, without inheritance, IQueryCustomizer<TModel> adds joins or filters, or replaces the search or sort entirely. Same three levels as the earlier engine’s IAdaptedSearch / IReplacableSearch / IReplacableSort interfaces: add, replace search, replace sort.


6. Mapping and database approach

6.1 Read (projection)

  • By convention: a model property Name maps to entity Name, and CityName flattens to City.Name.
  • The engine builds an Expression<Func<TEntity, TModel>> once per page and uses it in .Select(...), so the projection runs in SQL.

6.2 Computed fields

Declared as expressions, so they stay translatable:

public class PackageMapper : PageMapper<PackageModel, Package>
{
    public PackageMapper()
    {
        Compute(m => m.CanDelete,    e => !e.PackagePrograms.Any());
        Compute(m => m.ProgramCount, e => e.PackagePrograms.Count());
    }
}

A PageMapper subclass is discovered automatically when present, and most pages don’t need one. Like every extension class, its read and write methods are virtual (§7.1).

6.3 Write

  • Load the entity by key (update, through the tenant-filtered query) or create it (insert).
  • Copy only [Field] properties that aren’t [Computed] or [Key].
  • Lookups write the foreign key property.
  • Tenant id and audit columns are stamped by the engine, never taken from the request (§9).
  • Optimistic concurrency: a rowversion/concurrency token goes round-trip in the model, and a conflict returns 409.

6.4 Code-first and database-first, both first-class

The engine only needs a DbContext and entity types. It doesn’t care how they were produced.

  • Code-first: entities + migrations in C#. Tenancy and soft delete can be applied with a convention: modelBuilder.ApplyCrudConventions() adds TenantId/IsDeleted columns, indexes and query filters.
  • Database-first: dotnet ef dbcontext scaffold from an existing database. Page models sit in a separate project from the scaffolded entities, so re-scaffolding never overwrites them. Query filters are registered from a partial OnModelCreatingPartial, or by the engine at runtime via UseEntityFrameworkCore<TContext>(o => o.ApplyConventions = true).
  • The examples repo covers both paths with the same pages (§13).

6.5 DDD-compatible, not DDD-imposing

The engine is a CRUD engine. It serves simple tables and DDD aggregates, but it doesn’t force DDD on anyone and ships no DDD base classes (Entity, AggregateRoot, ValueObject). Those belong to the app’s Domain, and putting them in the engine would make Domain reference the engine, breaking “Domain references nothing” (§13.2).

DDD concern How the engine fits
Simple tables (lookups, settings) Default mapper copies [Field] values onto public setters.
Rich aggregates (private setters, behavior methods) The engine never writes private setters. If no public setter matches a field, it stops with a clear message telling you to override MapToEntityAsync in a mapper or service subclass. There you call the domain’s own methods (entity.Rename(model.Name)), so invariants stay in the Domain. Non-public constructors are allowed for CreateEntity, which can also be overridden to call a factory.
Read side Page models are read models projected in SQL (CQRS-lite): queries never load aggregates.
Invariant violations Domain code throws its own exceptions. Phase 2 adds o.MapException<TException>(status) in the Api, so the Domain never references engine exception types.
Domain events, interceptors Every save goes through the app’s own DbContext.SaveChangesAsync, so the app’s interceptors and event dispatch run unchanged.
Value objects EF Core owned/complex types work. Flattening maps AddressCity → Address.City by convention.
Aggregate boundaries A page normally targets an aggregate root. Child entities are edited through master-detail pages (phase 3) that go through the root’s service.

6.6 Read and write sides: stores, replicas and read models (CQRS)

Implemented in phase 3b. Free (MIT): it’s architecture, not an enterprise add-on. Three optional levels; an app that uses none of them works exactly as before.

Level 1: separate read and write stores. ICrudStore splits into:

  • ICrudReadStore: no-tracking queries and query execution (count, list, first, any).
  • ICrudWriteStore: tracked loads, add, remove, save, transactions.

The default EfCrudStore<TContext> implements both, so a single database needs nothing new. To read from a replica:

builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(primary));
builder.Services.AddDbContext<AppReadDbContext>(o => o.UseSqlServer(replica));   // same model, read-only connection

builder.Services.AddCrudEngine(o => o.AddPagesFrom(appAssembly))
    .UseEntityFrameworkCore<AppDbContext>()          // write side (and read side by default)
    .UseReadStore<AppReadDbContext>();               // read side: list, get

Level 2: consistency rules (built in, not optional). A replica can lag behind the primary, so the engine decides which side each read uses:

Read Side Why
List, get, schema data, lookups read normal traffic, the point of the replica
Reloading a row right after the caller’s own create/update write otherwise a new row could return 404
[Unique] checks (on save and the remote endpoint) write otherwise a duplicate could slip in during lag
Loading the row to update or delete, Updating.Original, Deleting.Model write must be the current state

As built: reads go through a per-page IPageReader<TModel> (default PageReader<TModel, TSource>, over the entity or the read entity), which uses the read store, or the write store when a consistent read is needed. The service’s ConsistentQuery() and LoadModelAsync(key, consistent) decide the rest, and every choice is a virtual method. Stores are chosen per page by ICrudStoreProvider, which is what tenant database routing (§9.5) replaces.

Level 3: a different read model (full CQRS).

[CrudPage("cities", Entity = typeof(City), ReadEntity = typeof(CityView))]
  • List, get, search and sort run against ReadEntity: a database view or a denormalized read table (pre-joined names, pre-computed totals). The page model is projected from it by the usual conventions.
  • Create, update and delete run against Entity. The consistent reads in level 2 then use Entity (or the view on the write database), never a stale read table.
  • Keeping a read table up to date is the app’s job, and events make it easy: an InTransaction handler for a synchronous update, or an after-commit handler (or outbox, later) for an eventual one. A database view needs no syncing at all.
  • Startup validation checks that every [Grid]/[Search] property maps to ReadEntity and every [Field] property to Entity.

Combined with tenancy (§9): the read side gets the same tenant scope; ReadEntity must carry the tenant property when the page is tenant-owned.

6.7 Hard and soft delete

[CrudPage(Delete = DeleteMode.Auto | Hard | Soft)]. Default Auto: soft when the entity has the soft-delete flag (bool IsDeleted, name set by SoftDeletePropertyName), hard otherwise, like TenantScope.Auto. CrudEngineOptions.DefaultDeleteMode changes the default app-wide. Startup fails when a page asks for Soft without the flag, when the flag isn’t a settable bool, when it’s a [Field], or when a soft page’s ReadEntity doesn’t carry the flag.

  • Delete sets the flag (and DeletedAt if the entity has a DateTime?/DateTimeOffset? property of that name). Deleting/Deleted events run as usual.
  • Hidden everywhere, enforced by the engine: the flag is applied with the fixed filters, so lists, get, lookups, foreign-key checks, update/delete loads and export never see deleted rows.
  • Like a foreign key: a soft delete is refused (409) while an active row of another page points at the row through a [Lookup] or [Parent] (any tenant), because the database can’t enforce it any more.
  • Deleted rows free their unique values: a new row may reuse them. Database unique indexes must then ignore deleted rows (HasIndex(...).IsUnique().HasFilter("IsDeleted = 0")). Restoring a row whose unique value is now used by an active row is refused (409) with the value to change first.
  • Deleted rows: ICrudService.ListDeletedAsync, RestoreAsync (same key) and PurgeAsync (removes it), with Restoring/Restored/Purging/Purged events (before-events can veto). HTTP: GET {page}/deleted, POST {page}/deleted/{id}/restore, DELETE {page}/deleted/{id}. Permissions crud:{page}:restore and crud:{page}:purge (new CrudAction.Restore / Purge); the schema says softDelete and both permissions. Purge is limited: only the host role or the exact crud:{page}:purge claim; wildcards (crud:*, crud:{page}:*) never grant it (PurgeNeedsExplicitPermission, default true).
  • Audit records restore and purge; restoring a soft-deleted row from History brings back the same row. UI: “Deleted items” on soft pages lists the rows with Restore and Delete permanently.
  • ICrudBehavior<TModel> wraps ListDeletedAsync, RestoreAsync, PurgeAsync and CreateWithKeyAsync too (default interface methods: existing behaviors are unaffected).
  • Computed values over navigations hide soft-deleted children once the model calls ApplyCrudConventions (§6.8); SQL views must still filter the flag themselves.

6.8 Audit fields and the Contracts package

Attritect.Contracts (a fifth free package: interfaces only, no logic, no dependencies, so a Domain layer can reference it): ISoftDelete, ICreationAudited, IModificationAudited, IDeletionAudited, IFullAudited, each with a string? user and a generic one (IFullAudited<Guid?>) for a foreign key to users.

  • How fields are found (AuditFieldResolver): Contracts interfaces, then the app’s own interfaces (o.MapAuditFields<IMyAudited>(m => m.IsDeleted(x => x.Removed)...), so a Domain can stay at zero references), then property names, case-insensitive (AuditFieldNameFor renames them). A bool that looks like a misspelled flag (IsDelete) is a startup warning (logged by MapCrudEngine), never silently a hard delete.
  • Who: ICrudUser (free); the ASP.NET Core package reads the signed-in user’s NameIdentifier/sub/name. The id is converted to the column type; an id that doesn’t fit (e.g. “alice” for int?) stays null.
  • Filling: an EF Core SaveChanges interceptor (registered by UseEntityFrameworkCore, also for tenant databases) stamps created at/by on insert, modified at/by on update (created values can’t be changed), and turns deletes of soft-delete entities into flag + deleted at/by, for engine writes and the app’s own saves. Real deletes: purge, pages with Delete = Hard, and db.HardRemove(entity).
  • Hiding: modelBuilder.ApplyCrudConventions(this) (call last) adds the EF Core 10 named query filter "SoftDelete", so the app’s own queries, navigations and counts hide deleted rows; switch it off with IgnoreQueryFilters(["SoftDelete"]). It also makes unique indexes ignore deleted rows (no more manual HasFilter) and sizes the “by” columns. The engine’s store switches the filter off only when it needs deleted rows.
  • Times: audit times are stored in UTC and read back marked UTC (a value converter from ApplyCrudConventions), so the API sends ...Z. The Blazor UI shows marked times in the browser’s time zone (or CrudUiOptions.TimeZone); times without a marker, such as a date-time a user entered, are shown as stored.

6.9 Compile-time checks (analyzers, implemented in phase 5d)

The startup rules are also Roslyn analyzers, shipped inside the Abstractions package (analyzers/dotnet/cs), so any project using the attributes sees mistakes in the editor and the build fails instead of the app failing at startup. Same rules and wording as PageMetadataProvider:

Id Severity Rule
CRUD001 Error [CrudPage] without Entity
CRUD002 Error no key (no [Key], no Id) or more than one [Key]
CRUD003 Error a key, [Search], sortable column, [Filter] or [Unique] that doesn’t map to the (read) entity
CRUD004 Error Contains/StartsWith on a non-text property
CRUD005 Error [Parent] without [Field]
CRUD006 Error DefaultSort field that doesn’t map
CRUD007 Error LookupText that isn’t a mapped text property
CRUD008 Error [Lookup]/[Parent] target that isn’t a [CrudPage] model
CRUD009 Error page model without a public parameterless constructor
CRUD010 Error two pages with the same id (reported on full builds)
CRUD011 Warning Delete = Soft without a visible flag (a MapAuditFields mapping can’t be seen at compile time)
CRUD012 Warning a bool that looks like a misspelled soft-delete flag (IsDelete)
CRUD013 Error soft-delete flag of the wrong type, used as a [Field], or missing on the ReadEntity
CRUD014 Warning [OwnRows] on an entity without a visible creator field (a MapAuditFields mapping can’t be seen at compile time)
CRUD015 Error [ScopeBy] property that isn’t on the entity, or an empty claim type
CRUD016 Error [Restricted] on the key, or a name that isn’t letters, digits and -
CRUD017 Warning [Restricted] on a non-nullable value type (hidden values come back as the default, e.g. 0)

Attributes are recognized by name in a namespace ending in .Abstractions (ISoftDelete in .Contracts), so a product rename keeps working. The analyzer targets netstandard2.0 with Roslyn 4.8 so it loads in older IDEs. Quick fixes: src/Analyzers.CodeFixes (a separate assembly, because code fixes need Roslyn’s Workspaces layer, which analyzers must not reference) ships next to the analyzer in the Abstractions package. The analyzer puts the fix and its data in each diagnostic’s properties (FixKinds), so the fix doesn’t repeat the analysis. Fixes: CRUD005, 009, 011, 012 (solution-wide rename), 013, 014, 016, 017; entity fixes find the entity’s source in any project of the solution. Not offered: “implement ISoftDelete” (the entity’s project may not reference Contracts; adding the property is enough).

Source generator (phase 5e). The same assembly holds an incremental generator, so every project using the attributes gets it:

  • Page catalog: [assembly: CrudPageCatalog(typeof(...), ...)] lists the types the engine registers (page models, service/mapper/query/reader subclasses, event handlers, behaviors). AddPagesFrom(assembly) reads it instead of scanning every type (UseGeneratedCatalog, default true), and trimming keeps the listed types. A test starts the engine both ways and requires identical service registrations.
  • Typed names: CrudPages.Course.Id, .Permission, .Fields.DurationWeeks ("durationWeeks", the same camelCase as the API) and .Claims.View ("crud:courses:view"), generated in each page model’s namespace.
  • Field writers: per page, an ICrudFieldWriter<TModel, TEntity> with direct assignments for every field that maps to a public setter of a compatible type; the mapper uses it first and falls back to reflection field by field (UseGeneratedWriters, default true). A test compares writers and reflection on every test page.
  • Not generated: the page metadata (attributes, read once at startup) and the read projection (an expression EF translates). EF Core itself isn’t AOT-ready, so full AOT isn’t a goal.

7. Services, hooks and the write pipeline

Save:   bind → validate (DataAnnotations + [Unique] + IValidator<T>) → hooks.BeforeSave
        → map to entity → stamp tenant/audit → SaveChangesAsync → hooks.AfterSave
Delete: authorize → load (tenant-filtered) → hooks.BeforeDelete (can veto)
        → soft delete if ISoftDelete, else remove → hooks.AfterDelete
  • Every page gets a default CrudService<TModel, TEntity>. To change one step, subclass it and override only that method (§7.1).
  • Page rules live in CrudPageEvents<TModel> classes (§7.0). ICrudHooks<TModel> from phase 1 was removed in phase 2b.

7.0 Events, behaviors and the two extension modes (implemented in phase 2b)

Two modes, each team picks one (an architecture test can enforce it):

  • Strict: Application references only Abstractions and customizes through events and behaviors.
  • Pragmatic: Application may also reference Core and override single methods by inheritance (§7.1).

Events. For every page: Listing/Listed, Viewing/Viewed, Validating, Creating/Created, Updating/Updated, Deleting/Deleted, plus custom events.

  • Before-events can change the model, add field errors (e.AddError → 400) or cancel (e.Cancel(reason) → 409). Listing can add a filter written on the page model, applied in SQL after the projection. Updating exposes the stored values (e.Original).
  • Page rules: one class per page, override only what you need (this replaces ICrudHooks):

    public class CityEvents : CrudPageEvents<CityModel>      // Abstractions only
    {
        protected override Task OnCreatingAsync(Creating<CityModel> e, CancellationToken ct) { ... }
        protected override Task OnDeletingAsync(Deleting<CityModel> e, CancellationToken ct)
        {
            if (e.Model.IsCapital) e.Cancel("Capital cities can't be deleted.");
            return Task.CompletedTask;
        }
    }
    

    Found automatically. Several per page are allowed, ordered by Order.

  • Cross-page and custom events: ICrudEventHandler<TEvent>. Every event also implements a general interface (ICreated, IUpdated, IDeleted, …), so one handler can cover all pages (audit, logging). Custom events: any class published through ICrudEventPublisher.
  • Domain events by convention: if an entity has a DomainEvents collection, the engine dispatches those events after commit and then clears it. Domain still references nothing.
  • Transaction phase per handler: after-events run after commit by default. A handler can opt into running inside the transaction (the engine then opens one for that save). If an after-commit handler fails, the caller still gets success and the error is logged; a setting switches that to 500.
  • No cost when unused: events without handlers are skipped (known at startup).

Behaviors (mediator pattern, built in, no library). ICrudBehavior<TModel> wraps whole operations (Create, Update, Delete, Get, List) and calls next(). A behavior can skip, retry, cache or transform the result. Use behaviors for wrapping concerns (caching, timing, special authorization); events cover everything else.

Execution order (Create): behaviors (outer → inner) → validation (attributes, [Unique]) → Validating → Creating → map → stamp → save (in-transaction handlers here) → commit → Created.

What Strict mode can’t do: change entity-level steps (how fields are copied onto the entity, stamping, query internals). Those need Pragmatic inheritance; rich entities can also use a domain adapter (ICrudDomainAdapter<TModel, TEntity>, Abstractions only), which replaces field copying with the domain’s methods.

As implemented:

  • Event classes, handler interfaces, CrudPageEvents<TModel> and ICrudBehavior<TModel> live in Abstractions. The publisher (CrudEventPublisher) and cache (CrudEventCatalog) are in Core, and every method on them is virtual.
  • Discovery: any ICrudEventHandler<T> or ICrudBehavior<TModel> in the scanned assemblies is registered. Generic behaviors (X<TModel>) apply to every page. For CrudPageEvents subclasses, only the overridden On...Async methods are registered, so an event nobody overrides is never even dispatched.
  • ICrudEventHandlerSettings (optional) gives a handler Order and Phase.
  • In-transaction handlers: the engine opens a transaction through ICrudStore.BeginTransactionAsync, or joins the app’s own transaction if one is already open.
  • Errors: AddError → 400, Cancel → 409 (403 for Listing/Viewing). An after-commit failure is logged unless o.ThrowOnAfterCommitFailure = true.
  • Errors are never swallowed. Validation returns 400 with field errors (ProblemDetails), a missing row (or another tenant’s row) returns 404, a concurrency conflict returns 409, and an FK-blocked delete returns 409 with a readable message. Everything else is logged and returns 500.

7.1 Override anything, one method at a time

This is a core principle, carried over from the earlier engine.

By default you write no controller and no service. When one page needs different behavior, you inherit from the engine’s base class and override only the method you want to change. The rest of the class keeps the default behavior.

Rules the engine follows

  1. Every extension class is a public, non-sealed base class, and every public and protected method on it is virtual. Extension classes:

    Class Role
    CrudController<TModel> HTTP actions (list, get, create, update, delete, unique, lookup, schema)
    CrudService<TModel, TEntity> Use-case pipeline: query, create, update, delete
    CrudQueryBuilder<TModel, TEntity> Filters, fixed filters, sorting, paging
    PageMapper<TModel, TEntity> Projection (read) and copying fields onto the entity (write)
    EfCrudStore<TContext> Persistence over the app’s DbContext: query, add, remove, save, error translation (UseEntityFrameworkCore<TContext>(typeof(MyStore)) to replace)
    ValueParser Text → typed values for filters and ids
    PageSchemaBuilder Builds the page schema JSON
    PageMetadataProvider Reads attributes into metadata
    default ICrudPermissionProvider / ITenantResolver implementations Authorization, tenant resolution
  2. Big operations are split into small virtual steps (template method pattern), so overriding one step never means copying the whole flow:

    CrudService.CreateAsync(model)
      ├─ ValidateAsync(model)            virtual
      ├─ OnBeforeSaveAsync(model)        virtual (runs hooks)
      ├─ CreateEntity()                  virtual
      ├─ MapToEntityAsync(model, entity) virtual
      ├─ StampAsync(entity)              virtual (tenant, audit columns)
      ├─ PersistAsync(entity)            virtual
      ├─ OnAfterSaveAsync(model, entity) virtual (runs hooks)
      └─ MapToModelAsync(entity)         virtual
    

    Every controller action follows the same shape: AuthorizeAsync → service call → ToActionResult, each step virtual.

  3. Three levels, picked automatically, most specific wins:

    Level How Applies to
    Engine default nothing to write every page
    App-wide base (the earlier engine’s BaseController) AddHttpApi(o => o.UseControllerBase(typeof(AppCrudController<>))), AddCrudEngine(o => o.UseServiceBase(typeof(AppCrudService<,>))) every page without its own class
    Page-specific a class deriving from CrudController<PackageModel> / CrudService<PackageModel, Package>, or from your app-wide base that page only
  4. No registration needed. AddPagesFrom(assembly) finds subclasses. Services are registered in DI as that page’s service, and controllers are picked up by the feature provider instead of the generated one. If two page-specific classes target the same page, startup fails with a clear message.
  5. Constructor-stable bases. Base classes take one dependency bundle (CrudControllerContext<TModel>, CrudServiceContext<TModel, TEntity>). Your subclass can add its own constructor dependencies, and when the engine adds a new internal dependency, your subclass still compiles.
  6. Call base.X() inside an override to keep the default behavior and add to it.

Examples

Change one controller action, keep all the others:

public class PackageController(CrudControllerContext<PackageModel> context)
    : CrudController<PackageModel>(context)
{
    public override async Task<IActionResult> Delete(string id, CancellationToken ct)
    {
        var package = await Context.Service.GetAsync(id, ct);
        if (package.IsDefault)
            return Problem("The default package can't be deleted.", statusCode: 409);

        return await base.Delete(id, ct);   // default behavior for everything else
    }
}

Change one service step, typed to the entity:

public class PackageService(CrudServiceContext<PackageModel, Package> context)
    : CrudService<PackageModel, Package>(context)
{
    protected override async Task MapToEntityAsync(PackageModel model, Package entity, bool isNew, CancellationToken ct)
    {
        await base.MapToEntityAsync(model, entity, isNew, ct);
        entity.Code = entity.Code.ToUpperInvariant();
    }
}

App-wide behavior for every page, with a page-specific class on top:

public class AppCrudController<TModel>(CrudControllerContext<TModel> context)
    : CrudController<TModel>(context) where TModel : class
{
    protected override IActionResult ToActionResult(object? result) { /* e.g. response envelope */ }
}

// Program.cs
builder.Services
    .AddCrudEngine(o => o.AddPagesFrom(appAssembly).UseServiceBase(typeof(AppCrudService<,>)))
    .UseEntityFrameworkCore<AppDbContext>()
    .AddHttpApi(o => o.UseControllerBase(typeof(AppCrudController<>)));

// a page that needs more derives from the app base, not the engine base
public class EmployeeController(CrudControllerContext<EmployeeModel> context)
    : AppCrudController<EmployeeModel>(context) { /* override one action */ }

Enforced by tests

An architecture test in the engine repo fails the build if any extension class is sealed, or if any of its public or protected instance methods is not virtual (or override). An analyzer in phase 5 gives the same feedback in the IDE.

Compatibility cost (accepted)

Virtual methods are part of the public API. Their signatures change only in major versions, and each release’s notes list any new virtual steps.


8. HTTP API and routing

Routes sit under a configurable prefix (default /api/crud):

Method & route Action Permission
GET /api/crud/pages Pages the user can see (for menus) authenticated
GET /api/crud/{page}/schema Page schema JSON (§10) view
GET /api/crud/{page}?page&size&sort&f.* List view
GET /api/crud/{page}/{id} One row view
POST /api/crud/{page} Create create
PUT /api/crud/{page}/{id} Update update
DELETE /api/crud/{page}/{id} Delete delete
GET /api/crud/{page}/unique/{field}?value&id Remote unique check create or update
GET /api/crud/{page}/lookup?q&take&ids { value, text } options for dropdowns, only rows the caller can see view on the lookup page

Generic controllers, with no class to write: an IApplicationFeatureProvider<ControllerFeature> adds a closed controller for every [CrudPage] model. It uses CrudController<TModel>, or the app-wide base if one is configured. If the app defines its own subclass for that model, the engine uses it instead, and only the methods it overrides change (§7.1).

OpenAPI: every page appears in the generated OpenAPI document with typed models, so a client can be generated for any frontend.


9. Multi-tenancy (v1)

Strategy for v1: shared database, tenant column. Every tenant-owned row carries a TenantId. The design leaves room for database-per-tenant later (pro, §14) through an ITenantConnectionResolver.

Implemented in phase 2.

builder.Services
    .AddCrudEngine(o => o.AddPagesFrom(appAssembly).UseMultiTenancy<int>())   // or <Guid>, custom property name
    .UseEntityFrameworkCore<AppDbContext>()
    .AddHttpApi(o => o.HostRole = "admin");

9.1 Resolving the tenant (HttpTenantContext, every step virtual)

  • A user belongs to several tenants: one tenant_id claim per membership (claim type configurable).
  • The active tenant comes from the X-Tenant header (configurable), or is the only membership. With several memberships and no header, tenant pages answer 403 (“select a tenant”). A header naming a tenant the user doesn’t belong to also gets 403. Switching is just sending another header.
  • The host role (o.HostRole) may work without a tenant (seeing across tenants) or pick any tenant.
  • Resolved once per request, lazily. Apps can replace ITenantContext entirely (subdomain, route, …).

9.2 Which pages are tenant-scoped

  • Tenancy = TenantScope.Auto (default): tenant-owned if the entity has the tenant property (TenantId by default), by convention, so Domain needs no engine interface. Otherwise not scoped.
  • TenantScope.Tenant: always tenant-owned. Startup fails if the entity has no tenant property.
  • TenantScope.Shared: global data. Everyone reads; only the host writes (others get 403).
  • TenantScope.SharedWithTenantRows (opt-in per page): shared rows (tenant null, written by the host) plus each tenant’s own rows. Tenants see both and change only their own. Needs a nullable tenant property.
  • Startup validates all of this, including that the tenant property type matches UseMultiTenancy<TKey>.

9.3 Isolation guarantees (enforced by the engine, not by page authors)

Enforcement lives in the engine (CrudQueryBuilder.ApplyTenantScope + CrudService), not in EF Core global query filters. That way it works with any DbContext without changes, Core stays free of EF Core, and every step is overridable. EF global filters remain a good additional safety net for an app’s own hand-written queries (a helper for that is planned).

Operation Rule
List / get / unique check Filtered to rows the caller may read (tenant’s rows; plus shared rows on SharedWithTenantRows)
Create Tenant stamped from ITenantContext. A tenant sent by the client is ignored, even if the model marks it [Field]. The host without a tenant creates shared rows on SharedWithTenantRows, and can’t create rows on tenant pages (403).
Update / delete Row loaded through the write scope, so another tenant’s row (or a shared row, for tenants) returns 404, not 403, which doesn’t reveal it exists. The tenant of a row never changes.
Unique checks Among the rows the tenant can see ([Unique(PerTenant = false)] for global uniqueness)
Lookups / FK writes Phase 3: a foreign key must point to a row visible to the current tenant
Permissions Checked per request; tenant-specific roles are up to the permission provider

9.4 Tests

The engine’s cross-tenant leak suite (TenancyTests) acts as tenant A against tenant B’s data for list, get, update, delete, create-with-forged-tenant, unique checks, tenant switching, host access, shared rows and shared pages. Deliberately disabling the tenant filter makes it fail (checked). The example repeats the key cases for its own pages.

9.5 Database per tenant, mixed with shared databases (routing implemented in phase 3b)

Decided: both models at once. Most tenants share one database; any tenant (typically a large or regulated customer) can have its own. It’s chosen per tenant in configuration, and the same app and pages serve both.

builder.Services.AddCrudEngine(o => o.AddPagesFrom(appAssembly).UseMultiTenancy<int>())
    .UseEntityFrameworkCore<AppDbContext>()
    .UseTenantDatabases(t =>
    {
        t.Host = config.GetConnectionString("Host");          // shared pages + host data
        t.Shared = config.GetConnectionString("Tenants");     // default for every tenant
        t.Dedicated(42, config.GetConnectionString("Tenant42"));  // tenant 42 has its own database
        // or: t.UseResolver<MyTenantDirectory>();            // read the mapping from a table / service
    });

How it works

  • ITenantConnectionResolver maps the active tenant to a connection: dedicated, shared, or “unknown”. The default reads configuration; apps plug in their own (a tenant directory table, a secrets vault).
  • The engine creates the app’s DbContext on the resolved connection for each request. No DbContext changes are needed.
  • Page routing by tenancy:

    Page tenancy Database used
    Tenant pages the tenant’s database (dedicated or shared)
    Shared pages (global data) the host database
    SharedWithTenantRows shared rows live in the host database and tenant rows in the tenant’s database. The list merges both, which needs a cross-database read, so v1 requires these pages to stay in the shared database (startup validates it), and a later version merges in the service.
    Untenanted pages the host database
  • The tenant filter stays on, even in a dedicated database. It costs almost nothing and protects against misrouting. It also makes moving a tenant between shared and dedicated a data copy plus a config change, with no code change.
  • Unknown tenant or missing connection: 403 with a clear message, never a fallback to another tenant’s data.
  • Read replicas per tenant database are not built yet: in tenant-database mode, reads use each database’s primary connection.
  • Known limits (by nature of separate databases): a flattened navigation (CityName from City.Name) can’t join across databases, and a database foreign key can’t point into another database. Keep related pages in the same database kind (tenant pages with tenant pages), or use a lookup without a database FK.
  • The host without an active tenant browses tenant pages in the shared tenant database only. Dedicated databases are reached by selecting that tenant.

Free vs pro (§14)

  • Free: ITenantConnectionResolver, per-request routing, configuration-based mapping, validation.
  • Pro: provisioning (create a database for a new tenant), migrations across all tenant databases, moving a tenant between shared and dedicated, health and size reports per tenant database.

10. Security

  • Every action is checked against crud:{permission}:{view|create|update|delete}, in the controller base, not left to each page. (The earlier engine protected only 3 actions, leaving save/delete/list open.)
  • Default (phase 2): ClaimsPermissionProvider. The user’s permission claims must contain crud:{page}:{action}, crud:{page}:* or crud:*. The host role is allowed everything. Deny by default: anonymous callers get 401, and signed-in callers without the permission get 403. GET /pages lists only the pages the caller may view.
  • Other storage (e.g. role-page-action tables like the earlier engine’s) plugs in by implementing ICrudPermissionProvider. Decided: an optional package will store roles and page permissions in the database, with pages to manage them.
  • AddHttpApi(o => o.AllowAllPermissions = true) exists for local experiments only and logs a warning.
  • App exceptions → HTTP: o.MapException<MyDomainException>(409) turns an app or domain exception into a problem response with its message, so the Domain never references engine exception types.
  • Allow-list binding: only [Field] properties are writable, and only [Search] properties are filterable or sortable.
  • Tenant isolation as in §9.3.
  • Antiforgery for cookie-authenticated posts. Bearer tokens for SPA/mobile clients.
  • No HTML in the engine. Renderers use components with automatic encoding.

11. Page schema (renderer contract) and renderers

The engine turns metadata into a renderer-neutral JSON schema. In v1 this is the UI contract: apps can build their own screens on the API + schema right away.

{
  "schemaVersion": 1,
  "page": "nationalities",
  "title": "Nationalities",
  "itemTitle": "Nationality",
  "key": "id",
  "tenancy": "tenant",
  "permissions": { "create": true, "update": true, "delete": false },
  "columns": [
    { "name": "id",   "title": "Code", "sortable": true, "type": "int" },
    { "name": "name", "title": "Name", "sortable": true, "type": "string" }
  ],
  "search": [
    { "name": "name", "label": "Name", "op": "contains", "input": "text" }
  ],
  "fields": [
    { "name": "name", "label": "Name", "input": "text", "required": true,
      "maxLength": 100, "pattern": "^[^<>]*$", "unique": true }
  ],
  "rowActions": [ { "id": "edit" }, { "id": "delete", "enabledBy": "canDelete" } ],
  "defaultSort": [ { "name": "name", "dir": "asc" } ]
}
  • Titles and labels are resolved through IStringLocalizer for the request culture (Arabic/English at least). Attribute strings are resource keys, or literal text as a fallback.
  • permissions reflect the current user and tenant, so a renderer simply shows or hides buttons.
  • Validation rules are in the schema, so client-side validation needs no extra code.
  • Dates are exchanged in ISO format (Gregorian). Display calendar (Gregorian or Hijri Umm al-Qura via .NET’s UmAlQuraCalendar) and text direction are hints in the schema, applied by renderers.

Localization (implemented in phase 4, free). Call UseLocalization<TResource>() (any IStringLocalizer source, e.g. .resx). Every title, label, placeholder, row-action label, lookup text and engine message (validation, conflict, not found) is a resource key with the literal text as the fallback. The schema carries culture, direction (ltr/rtl) and calendar (gregorian/umAlQura, from DisplayCalendar), taken from the request culture (UseRequestLocalization). CrudText is the one virtual place that translates.

Renderers (pro). The first renderer is Blazor (Attritect.Pro.Ui.Blazor, in the private pro repo). It serves every page at {BasePath}/{page} (default /admin/{page}) with zero per-page markup: navigation by group, grid with sort and paging, search form, add/edit dialog by field type, lookups as selects, master-detail through child row actions (?f.parentId=1, the parent field fixed in the form), server-side field errors, delete confirmation, RTL and Hijri display. Built with its own components, no third-party UI library, themed with CSS variables (attritect.css).

  • It talks to the engine’s HTTP API through CrudUiClient (every method virtual). Auth headers, tenant and language are added by ICrudUiRequestHandler implementations, so the UI works the same for a same-app Interactive Server UI or a separate front end (ApiBaseAddress).
  • Its own button texts come in English and Arabic; CrudUiOptions.Texts adds or overrides any language.
  • Hijri pages get an own Umm al-Qura date picker (typed or picked; the value stays Gregorian ISO).
  • AddCrudUiInProcess(): Interactive Server apps that host the API call it in memory through their own pipeline (captured by a startup filter), as the circuit’s user; WebAssembly or a separate API use HTTP.

12. Performance

  • Metadata is built once at startup: reflection runs only there, and results are cached in frozen collections with compiled getters and setters.
  • All queries are SQL-side and async. Projection selects only the needed columns.
  • Lookups support take + q (autocomplete) instead of loading full tables.
  • Phase 5: a source generator emits metadata and accessors at compile time, for no startup reflection and trimming/AOT friendliness.

13. Engine repo, examples repo, and Clean Architecture

13.1 Two repositories

The engine is a product. The examples are customers of the product. They live in separate repos, so the engine can never quietly depend on app code:

Repo Contains
Attritect (this repo) Engine packages, engine tests, design docs. No example or domain code. Engine tests use their own tiny test models.
Attritect.Examples Every example app. The main example is Clean Architecture. More are added as needed.
  • Examples consume the engine only as NuGet packages, never project references. During development, build.ps1 in this repo packs the engine into artifacts/packages, and the examples repo’s nuget.config points at that folder. Package source mapping routes Attritect.* to that feed only. Later the feed becomes a private or public NuGet server. If something works in an example, it works for a real buyer.
  • Each example pins an engine version, so the examples also act as compatibility tests across releases.
  • Pro packages (§14) can later get their own private repo without touching either of these.

13.2 Using the engine in Clean Architecture (the main example)

The engine fits Clean Architecture without bending it. The one design rule that makes this work: the Application layer depends only on the framework-free engine packages: Abstractions (attributes, interfaces) and, when it subclasses services, Core. Never on EF Core or ASP.NET Core. Controller subclasses live in Api, and store subclasses in Infrastructure.

            ┌──────────────────────────┐
            │  SampleApp.Api           │  Program.cs, auth, HTTP tenant resolver,
            │  + Engine.AspNetCore     │  AddCrudEngine(), MapCrudEngine() (composition root)
            └───────┬──────────┬───────┘
                    │          │
       ┌────────────▼───┐   ┌──▼──────────────────────┐
       │ SampleApp.     │   │ SampleApp.Infrastructure │  AppDbContext, EF configurations,
       │ Application    │◄──┤ + Engine.EntityFramework │  migrations, external services
       │ + Engine.      │   │   Core                   │
       │   Abstractions │   └──────────┬───────────────┘
       └───────┬────────┘              │
               │                       │
           ┌───▼───────────────────────▼──┐
           │ SampleApp.Domain             │  entities, value objects, domain rules
           │ (no references at all)       │
           └──────────────────────────────┘
Layer Contains References
Domain Entities (Nationality, City, Package, Program, PackageProgram), domain rules Nothing, not even the engine. Tenancy and soft delete are detected by convention (TenantId, IsDeleted properties), so entities need no engine interface.
Application Page models ([CrudPage] classes: these are the app’s DTOs/read models), PageMappers for computed fields, ICrudHooks<T>, service subclasses (CrudService<,> overrides), validators, hand-written use cases for non-CRUD workflows Domain + Engine.Abstractions (+ Engine.Core when subclassing services)
Infrastructure AppDbContext, entity configurations, migrations or scaffolded model, external services Application + Domain + Engine.EntityFrameworkCore. No ASP.NET Core.
Api Composition root: DI, auth, the HTTP-based ITenantResolver (claims/header/subdomain), AddCrudEngine(), MapCrudEngine(), custom controllers that override CrudController<T> All of the above + Engine.AspNetCore

Why page models live in Application, not Domain: they describe how data is presented and edited (columns, search, form fields). That’s the job of DTOs/view models in Clean Architecture. Domain entities stay pure.

Non-CRUD work (approvals, payments, reports) is written as normal Application use cases next to the engine-driven pages. The engine handles the repetitive 80%, and the architecture holds the other 20%.

Architecture tests in the example fail the build if Domain uses anything beyond the .NET base library, if Application uses EF Core, ASP.NET Core, outer layers or any engine package other than Abstractions/Core, or if Infrastructure uses ASP.NET Core or the Api. They’re plain reflection over each layer’s compiled references, with no extra library. The compiler drops unused references, so only real usage counts. The engine repo applies the same technique to its own package boundaries (§3.2).

Code-first and database-first (§6.4) are separate examples with the same four layers. They can’t be merged into one app with swappable infrastructure, because in database-first the entities are generated from the database, so the Domain can’t be shared. The examples repo’s README lists all examples and their layouts.

13.3 Engine repository layout

Attritect/
  docs/design.md
  Attritect.slnx
  Directory.Build.props              # EngineName, net10.0, nullable, warnings as errors
  Directory.Packages.props           # central package versions
  build.ps1                          # restore → build → test → pack to artifacts/packages
  src/
    Abstractions/  Core/  EntityFrameworkCore/  AspNetCore/
  global.json                        # SDK 10.0.4xx + Microsoft Testing Platform runner
  tests/
    Architecture.Tests/              # package boundaries + naming rules (phase 0)
    Core.Tests/                      # expression builder → ToQueryString() assertions (phase 1)
    AspNetCore.Tests/                # auth, binding, errors, tenant leak suite, own test models (phase 1–2)
  scripts/rename.ps1
  artifacts/                         # git-ignored: packed .nupkg files (local feed)

14. Open core and pro

Free (MIT) Pro (commercial), proposed
Attributes, metadata, page schema UI renderers: generic admin UI, own component set, RTL, Hijri date picker
SQL query engine, mapping, hooks Audit & history: who/when/what diff, restore previous version
EF Core store, code-first & database-first Import / export: Excel/CSV import with validation, Excel/PDF export
HTTP API, OpenAPI, permissions Tenant database tooling: provisioning, migrations across tenant databases, moving a tenant between shared and dedicated (§9.5)
Read/write stores, read replicas, read models (§6.6); tenant database routing, shared + dedicated mix (§9.5)  
Multi-tenancy (shared DB, full isolation) Later: workflows/approvals, dashboards
Analyzers + source generator  

Principle: security and correctness are never paywalled. Tenant isolation, permissions and validation stay free. Pro sells productivity and enterprise features.

14.1 Separate packages, activated by a license key

Pro features ship as separate, closed-source packages, and a license key activates them. Both are needed:

  • Why separate packages: the free packages are MIT-licensed open source. Anyone may legally modify them, so a key check inside free code could simply be deleted. Pro code is only protected when it lives in its own packages under a commercial license.
  • Why a key: it lets pro packages be published openly (easy install, works as a trial) while only licensed customers use them in production, and it lets one package hold several tiers.
  Free Pro
Packages Attritect.Abstractions, .Core, .EntityFrameworkCore, .AspNetCore, .Analyzers Attritect.Pro.Licensing (key validation, shared), .Pro.Ui, .Pro.Audit, .Pro.ImportExport, .Pro.TenantPerDatabase, and the meta-package Attritect.Pro (references all of them)
License MIT, source on public repo Commercial EULA, closed source, separate private repo
Key never needed one key unlocks every pro package and tier the customer bought
Distribution nuget.org nuget.org (trial-friendly). A private feed is possible later.

Dependency direction: pro packages reference free packages and plug in only through the public extension points (virtual methods §7.1, interfaces, DI). Free packages never reference pro code. An engine architecture test enforces this. So anything a pro package does, a customer could build on the free core, and the open-core promise stays honest.

14.2 The license key

Format (implemented in phase 5a): AE1.{payload}.{signature}, both base64url. The payload is the license JSON; the signature is ECDSA P-256 / SHA-256 (built into .NET; .NET has no built-in Ed25519 and the engine takes no third-party dependencies). Validated offline with the public key embedded in LicenseVerifier.VendorPublicKey. The private signing key never leaves the vendor’s machine and is never committed.

{
  "licenseId": "L-2026-0042",
  "licensee": "Example Co.",
  "edition": "Pro",                     // Pro | Enterprise
  "features": ["ui", "audit", "import-export"],
  "maxTenants": null,                   // optional: passing it logs a warning (counted from page operations)
  "issued": "2026-12-01",
  "updatesUntil": "2027-12-01",         // covers every release built before this date
  "expires": null                       // null = perpetual for covered versions
}

Supplying the key: configuration (Attritect:LicenseKey), environment variable, or a license.key file next to the app:

builder.Services.AddProLicense(o => o.LicenseKey = "...");   // optional: every pro package adds licensing itself

The key is looked up in this order: ProLicenseOptions.LicenseKey, configuration Attritect:LicenseKey (so also the environment variable Attritect__LicenseKey), then a license.key file in the app folder. Each pro package registers its feature (AddProFeature("ui", assembly)); ProLicenseReporter (a hosted service) logs each feature’s state at startup and, while any is unlicensed, once a day. ProLicense.IsLicensed(feature) is available to pro code, but no pro feature blocks on it.

Rules: | Situation | Behavior | |—|—| | Valid key covering the feature and this release | Works silently | | No key, Development environment | Fully works, with one startup warning (“trial / unlicensed”) | | No key or invalid key, Production | Still works. A clear warning is logged at startup and once per day. It never blocks or breaks a customer’s production system. | | Release built after updatesUntil | Treated as unlicensed for that release (same warnings). Older covered releases keep working forever. | | Feature not in the key | That pro feature logs a warning and runs in trial mode |

  • No phone-home, no telemetry. Validation is purely local, so it works on air-gapped and restricted networks (common for government and enterprise customers).
  • Licensing by version: each pro build embeds its build date. A key covers all builds dated before updatesUntil. Renewal extends updates. Customers never lose versions they paid for.
  • No obfuscation effort. .NET IL is easy to decompile. The key keeps honest companies honest, and the EULA is the real protection. Effort goes into the product, not into anti-cracking.
  • Vendor tooling: tools/LicenseTool in the pro repo (keygen, issue, verify), never packed or shipped. A license portal is out of scope until there are customers.

14.3 Audit and history (implemented in phase 5b, pro)

Packages: Pro.Audit (no ASP.NET Core, so a Clean Architecture Infrastructure layer can map the table) and Pro.Audit.AspNetCore (the signed-in user and the HTTP API).

modelBuilder.AddAuditTrail();                          // in each DbContext the engine writes to
builder.Services.AddCrudEngine(...).AddHttpApi().AddHttpAudit(o => o.ExcludeField("users", "password"));
app.MapCrudAudit();
  • Capture: one handler (AuditRecorder) on ICreated, IUpdating, IUpdated and IDeleted records page, row key, action, tenant, user, UTC time and the [Field] values before and after (JSON). Updates that change nothing are skipped. Pages and fields (secrets) can be excluded.
  • Same database, same transaction: it writes through ICrudStoreProvider.WriteStore(page), so each entry lands in the row’s own database (tenant databases included), and by default it runs InTransaction: a failed audit write rolls the change back. Phase = AfterCommit keeps the change and logs the failure instead.
  • History (AuditHistory, every method virtual): GET {page}/{id}/history (newest first, with the changed fields) and GET {page}/history/recent?action=delete (deleted items). Needs the page’s View permission. Callers see only entries made under their own tenant; the host sees all.
  • Restore: POST {page}/{id}/history/{entryId}/restore puts the row back to that entry’s values through the page’s normal service: Update (needs Update), or Create for a deleted row (needs Create, may get a new key). Validation, events and the audit itself all apply.
  • UI: AddCrudUi(o => o.ShowHistory = true) adds “History” on rows (changes, who, when, restore) and “Deleted items” on pages.
  • Hard-deleted rows come back under their old key (RestoreWithSameKey, default true) through the engine’s free ICrudService.CreateWithKeyAsync, so links and history continue. If the key is taken or the database refuses explicit keys, the restore falls back to a new key (result keyReused: false). On SQL Server identity columns the EF store switches IDENTITY_INSERT on for that one save (ICrudWriteStore.AddWithKeyAsync, tested on LocalDB). Deleted items list the newest delete per row and leave out rows that exist again.
  • Retention: KeepFor / KeepVersions with a scheduled cleanup (AddAuditCleanup<TContext>()); a row’s newest entry is always kept.

14.4 Import and export (implemented in phase 5c, pro)

Packages: Pro.ImportExport (no ASP.NET Core) and Pro.ImportExport.AspNetCore (HTTP API).

builder.Services.AddCrudEngine(...).AddHttpApi().AddImportExport();
app.MapCrudImportExport();
  • Formats, no library: Excel (.xlsx) is written and read with ZipArchive + XmlReader/XmlWriter (typed cells, bold frozen header, right-to-left sheets; shared/inline strings, dates by number format; safe XML, zip-bomb guard). CSV is RFC 4180, UTF-8 with BOM (Arabic in Excel), separator detection, and formula neutralizing (CSV injection). More formats: register an ITableFormat.
  • Export (GET {page}/export/{format}, needs View): the grid’s columns and translated titles, the same f.* filters and sort, every matching row (up to MaxExportRows), read through the page service.
  • Import (POST {page}/import/{format}?dryRun=true, needs Create; template at GET {page}/import/template/{format}): columns match fields by label (translated or not) or name; lookups accept the option text (case-insensitive) or the id; Arabic-Indic digits are accepted. Every row is checked first with the engine’s new free ICrudService.ValidateAsync (field rules, unique values, references, Validating handlers) plus values repeated in the file. Rows are created only when the whole file is valid, one by one through the service (tenant stamping, events, audit). The report lists problems by sheet row and field, ignored columns and missing required columns.
  • PDF: the UI’s Print view (all matching rows, print stylesheet) uses the browser’s Save as PDF, which renders Arabic correctly. A server-side PDF writer would need font embedding and Arabic shaping: that is library-sized work, deferred.
  • UI: AddCrudUi(o => o.ShowImportExport = true) adds Export (Excel, CSV), Print and Import (template, Check, Import, per-row report) to every page; child pages fix the parent automatically.
  • Known gaps: rows are created one by one after the check, so a change between the check and the save (e.g. someone adds the same unique value) stops the import part-way, with the rows before it kept; no update-by-key (“upsert”) import yet; one sheet per workbook.

14.5 Feature boundaries can still move

The free/pro table above is a proposal (see §16 “Still open”). Because pro features are add-on packages using public extension points, moving a feature from pro to free later is just a package move. Moving one from free to pro is never done: what was free stays free.


15. Roadmap

Phase Deliverable Proven by
0. Skeleton ✅ done Engine solution, Directory.Build.props (EngineName), central packages, build.ps1 (build → test → pack to local feed), CI, rename script. In the examples repo: the Clean Architecture example’s four layers + architecture tests, referencing the packed packages. CI green; the main example restores and builds from the local feed
1. Core + EF + API ✅ done Attributes, metadata, SQL query engine, projection, CRUD service, HTTP API, schema endpoint, ProblemDetails, OpenAPI Nationality, City pages over HTTP, every query verified as SQL
2. Security + tenancy ✅ done Claims permissions (deny by default, 401/403), host role, tenant resolution with switching, engine-enforced scoping (tenant, shared, shared + tenant rows), stamping, per-tenant unique, exception mapping, cross-tenant leak suite Leak suite green (and fails when the filter is disabled)
2b. Events & behaviors ✅ done CrudPageEvents<TModel> (replaces hooks), ICrudEventHandler<T>, custom + domain events, transaction phase per handler, ICrudBehavior<TModel>, Strict/Pragmatic architecture tests The example’s capital-city rule moves from a controller override to a CityEvents class; a cross-page audit handler logs every create
3. Relations & both DB paths ✅ done [Lookup] + lookup endpoint (tenant-safe foreign keys), [Parent] master-detail, [RowAction] + automatic child actions, schema parent/children/lookups; code-first and database-first examples Packages → Package courses (Courses as lookup) in both examples
3b. Read/write & tenant databases ✅ done ICrudReadStore/ICrudWriteStore split, UseReadStore<T>(), consistency rules, ReadEntity (views / read tables); ITenantConnectionResolver, UseTenantDatabases with a shared + dedicated mix, host database for shared pages Example reads lists from a view; one tenant on its own database while two others share one, and the leak suite passes across both
4. Localization + first renderer (pro) ✅ done ar/en (UseLocalization<T>, translated schema + messages), RTL/Hijri hints, Blazor generic UI with own components (pro repo) Every example page usable at /admin in English and Arabic with no per-page markup, including Packages → Package courses
5a. Licensing (pro) ✅ done Pro.Licensing (offline ECDSA-signed keys, build-date coverage, features, expiry, startup + daily warnings), license-tool (keygen / issue / verify), the Blazor UI registered as the ui feature Tampered, foreign, expired and not-covered keys are rejected in tests; the example logs a trial warning and keeps working
5b. Audit & history (pro) ✅ done Pro.Audit + Pro.Audit.AspNetCore: in-transaction audit in the row’s own database, history and deleted-items API with tenant isolation, restore through the page service; Blazor History / Deleted items Unit tests (rollback, isolation, restore, permissions) and HTTP tests in the example; restore verified in the browser in English and Arabic
5c. Import & export (pro) ✅ done Pro.ImportExport + .AspNetCore: own xlsx/CSV reader-writer, grid export, check-first import with lookups by text and a per-row report; free ICrudService.ValidateAsync; Blazor Export / Print / Import Unit tests (formats, import rules, tenancy, permissions) and HTTP tests in the example; export, check, import (Arabic headers and digits) and print verified in the browser
5d. Analyzers ✅ done Startup rules as compile-time errors/warnings (CRUD001–CRUD017), shipped inside the Abstractions package Each rule tested on an in-memory compilation; a broken example page fails the build with the same message the startup would give
5e. Source generator ✅ done (first part) Page catalog (no type scanning at startup) and typed names (CrudPages.X.Id/Fields/Claims) Engine registrations identical with and without the catalog; a generator that drops a type fails the tests; the example uses CrudPages.Course.Id
5f. Docs and packaging ✅ done User guide (docs/README.md, 10 pages; pro guide), package READMEs and validation, changelogs, verify-packages.ps1 on every build, publish.ps1 (dry run by default), release workflow with approval, CI for pro and examples A preview version packs, verifies and dry-runs; a package without a README fails verification
5. Productize (rest) Generated metadata/mapping (optional), analyzer code fixes, first publish (needs the final name), use in one real project Used in one new real project

Phase 1 definition of done: the Nationality page works over HTTP with search, sort, paging, create, update, delete and the unique check, and no query is evaluated in memory. The override rules (§7.1) hold: the virtual-methods architecture test passes, and the example contains one page with a controller subclass and one with a service subclass, each overriding a single method, with tests proving the other methods keep their default behavior.


16. Decisions

# Question Decision (2026-11-24)
1 Product name Attritect, changeable via EngineName (§3.1)
2 First UI API + schema for v1; the first renderer is Blazor (phase 4, pro, §11)
3 UI component library Own components, no third-party library
4 Database approach Both code-first and database-first, first-class
5 Licensing Open core (MIT) + paid pro packages (§14). Pro features ship as separate closed-source packages, activated by one offline-verified signed license key. A missing or expired key warns but never blocks production. Licensing is by version. No phone-home. (§14.1–14.2)
6 Multi-tenancy Yes, in v1: shared database + tenant column (§9)
7 Engine vs. examples Separate repos: Attritect (engine only) and Attritect.Examples; examples consume NuGet packages only (§13.1)
8 Main example Clean Architecture (Domain / Application / Infrastructure / Api); Application depends only on framework-free engine packages, Abstractions and Core (§13.2). More examples are welcome.
9 Extensibility Override anything, one method at a time: every extension class is non-sealed and every public/protected method is virtual. No controller or service by default; page-specific and app-wide subclasses are picked up automatically (§7.1). Enforced by an architecture test.
10 DDD DDD-compatible, not DDD-imposing: no DDD base classes in the engine; private setters are never written; aggregates customize writes by calling domain methods in a mapper or service override (§6.5).
11 Extension modes Strict (Application → Abstractions only; events + behaviors) and Pragmatic (+ Core inheritance); each team chooses (§7.0)
12 Events vs hooks Both kept as concepts, one pipeline: page rules are CrudPageEvents<TModel> (override what you need); cross-page and custom events use ICrudEventHandler<T> (§7.0)
13 After-event timing After commit by default; a handler can opt into the transaction. A failed after-commit handler: success + log (setting for 500)
14 Mediator The pattern, built in. No MediatR or other third-party library.
15 Tenancy rules Several tenants per user with switching; SharedWithTenantRows opt-in per page; host role; enforcement in the engine, not EF filters (§9)
16 Permissions Claims-based default, deny by default; optional database-backed package with management pages (§10)
17 Text case Follows the database unless [Search(Case = ...)] or CaseInsensitiveText says otherwise (§5)
18 Read/write (CQRS) Free, three optional levels: read/write store split (replicas), built-in consistency rules (own-write reloads and unique checks hit the write side), and a separate ReadEntity per page (§6.6)
19 Tenant databases Shared and dedicated together: any tenant can have its own database while others share one, set per tenant; shared pages use a host database; the tenant filter stays on everywhere. Routing is free; provisioning and migration tooling is pro (§9.5)
20 Localization Free, through IStringLocalizer; attribute texts are resource keys with literal fallback; schema carries culture, direction and calendar (§11)
21 Pro repo Attritect.Pro is a separate private repo with its own build and local feed; pro packages reference only free packages; examples consume them by package (§14)
22 License signature ECDSA P-256 instead of Ed25519: built into .NET, no third-party library; same offline model (§14.2)
23 Audit storage In the app’s own database, same transaction by default, through the page’s write store (tenant databases included); history is tenant-private; restore goes through the normal service (§14.3)
24 Import/export Own .xlsx and CSV code (no library); import is check-first and creates only when the whole file is valid; PDF through the browser’s print (Arabic-safe), server PDF deferred (§14.4)
25 Delete mode [CrudPage(Delete = ...)], default Auto: soft when the entity has IsDeleted, hard otherwise; deleted rows hidden by the engine, free their unique values (restore refuses a duplicate), can’t be deleted while referenced; restore permission, purge only for the host or an explicit crud:{page}:purge (§6.7)
26 Restore key Restoring a hard-deleted row reuses its old key when the database allows it, else a new key; soft-delete pages always keep the key (§6.7, §14.3)
27 Audit fields Fifth free package Contracts (interfaces only) plus “bring your own interface” mapping and case-insensitive names with typo warnings; string? or generic user key; filled by an EF save interceptor (all saves); EF named filter "SoftDelete"; UTC DateTime (§6.8)
28 Field and row access [Restricted("name")] fields (claims {name}:view / :edit, read-only keeps the stored value); row rules [OwnRows], [ScopeBy], ICrudRowRule<T>, skipped by crud:{page}:all; named rights only by exact claims or the host role (never wildcards); enforced in pro export, import and history too

Still open

  1. Pro boundaries: confirm the table in §14 before phase 4. Is the database-backed permissions package free or pro? (Suggestion: permission checks stay free; the admin pages could be pro.)
  2. Domain adapter: implemented as ICrudDomainAdapter<TModel, TEntity> (create via a factory, update via behavior methods, an optional delete hook); domain events from it are dispatched as usual.

Appendix A: Earlier engine → Attritect

Earlier engine Attritect
GenericModel base class + SetPublicSettings(...) [CrudPage(...)] on a plain class (no base class)
ViewGridBaseController<T> (empty subclass per page), all actions virtual Automatic CrudController<T>; subclass only to override; all actions still virtual (§7.1)
App BaseController shared by all pages AddHttpApi(o => o.UseControllerBase(typeof(AppCrudController<>))) (§7.1)
Service replaced via constructor overload ViewGridBaseController(IManageBaseService<T>) Subclass CrudService<TModel,TEntity> and override one step; picked up automatically
ManageBaseService<T> + facilitator<T> + reflection-built repository ICrudService<T> default + ICrudStore (EF Core)
Entity found by scanning the mapper’s registered maps Entity = typeof(...) on [CrudPage]
BuildExpression (reflection lambdas, compiled, in-memory) Typed expression trees, AndAlso/OrElse, SQL-translated
Dynamic OrderBy expression builder Same idea, kept (it was already correct), with a sortable whitelist
HTML string helpers for grid and search form Page schema JSON (+ pro renderers)
Shared Razor views + one AngularJS controller v1: API + schema; later: generic renderer
Permission attribute on 3 actions + closed permissions DLL Policy on every action + ICrudPermissionProvider
Manual change-logging service Audit interceptor (pro)
[Remote("CheckDuplicate", …)] per model [Unique]
50+ fixed-length string attributes [SafeText(n)], standard [StringLength]
No tenancy Shared-DB tenancy with enforced isolation

Appendix B: Earlier bugs not to repeat

  • GetById<TOther>() permanently switched the service to another table.
  • Save hard-coded "ID" even though the key column was configurable.
  • The date-equals operator compared against an empty string when given a column name.
  • Contains/Equals operators threw on null column values.
  • The between operator supported only int.
  • A static model field was shared across requests.
  • The repository swallowed every exception, so failures came back as null/false.