The IEntityService is the core service interface for managing entities. It provides standard CRUD operations and can be customized or extended as needed.
Possible combinations:
IEntityService<TEntity> // int ID
IEntityService<TEntity, TKey>
IEntityService<TEntity, TKey, TSearchObject>
IEntityService<TEntity, TSearchObject, TSortBy, TIncludes>
IEntityService<TEntity, TKey, TSearchObject, TSortBy, TIncludes>
EntityRepository. It hands reads to EntityReadService and writes to
EntityWriteService, both working on the EF Core DbContextDbContext’s SaveChanges, reactors once it is committedHasRepository (derive from EntityRepository) or UseEntityService
(wrap it) — see Replacing the repository for one entityEntityRepository for every entity at once with UseRepository — see Replacing the repository app-wideflowchart TB
caller["Controller · mapped endpoint · job"] -- request --> sender["IEntitySender"]
caller -. direct call .-> service
sender --> handler["Request handler"]
handler -- "input DTO → entity<br/>entity → DTO" --> mapper["IEntityMapper"]
handler --> service["IEntityService"]
mapper --> engine["Mapster or AutoMapper"]
mapper --> after["AfterMappers<br/>After · AfterInput"]
service -- default --> repo["EntityRepository"]
repo --> read["EntityReadService"]
repo --> write["EntityWriteService"]
read --> qb["Query builders<br/>global filters · filters · sorting · includes"]
read --> proc["Processors"]
write --> prep["Preppers"]
write --> val["Validators"]
read --> db[("DbContext")]
write --> db
db --> icpt["SaveChanges interceptors<br/>primers · normalizers · reactors"]
classDef helper fill:#fff4d6,stroke:#c9a227,color:#000
classDef choice stroke-dasharray:5 5
class after,qb,proc,prep,val,icpt helper
class engine choice
The highlighted boxes are the helper services an application registers, and the dashed one is the mapping engine it
picks with UseMapsterMapping() or UseAutoMapper() — the engine’s package supplies the IEntityMapper, which runs
the AfterMappers once the engine has mapped. The others are the framework’s defaults.
The endpoints send their requests through IEntitySender (Entity Operations),
which adds what an endpoint answers — paging defaults, DTO mapping, the re-read after a save. Code that calls
IEntityService directly gets the same filters, preppers and validators without those.
A list or details read builds one query, runs it, and hands the rows to the processors:
flowchart LR
so["Search object<br/>sort · includes · paging"] --> filters["Filters<br/>global + entity"]
filters --> sort["Sorting"] --> page["Paging"] --> incl["Includes"] --> query[("Query")]
query --> proc["Processors"] -. entity operations .-> map["Mapping<br/>+ AfterMappers"]
A save, as the SaveCommand of a POST or PUT runs it:
sequenceDiagram
participant E as Endpoint or sender
participant H as SaveCommand handler
participant M as IEntityMapper
participant S as IEntityService
participant D as DbContext
participant R as Reactors
E->>H: SaveCommand(input DTO)
H->>H: check the input DTO (DataAnnotations)
H->>M: map input DTO to entity (+ AfterInput)
opt update
H->>S: does the row exist? (else 404)
end
H->>S: Save(entity)
S->>S: preppers, then validators (400 on a refusal)
S->>D: track the entity
H->>S: SaveChanges()
S->>D: SaveChanges()
D->>D: primers, normalizers, write and commit
D-)R: committed changes, in a DI scope of their own
H->>S: Details(id) with includes and processors
H->>M: map entity to DTO (+ AfterMappers)
H-->>E: SaveResult
The controllers leave the input check to MVC, which has answered an invalid request body by then. A delete runs the validators too, against the row as stored, and no prepper.
// Get single entity details by ID
Task<TEntity?> Details(TKey id, CancellationToken token = default)
// List with custom SearchObject (enhanced filtering)
Task<IList<TEntity>> List(TSearchObject? so = null, PagingInfo? pagingInfo = null, CancellationToken token = default)
// List with sorting and includes (complex filtering)
Task<IList<TEntity>> List(IList<TSearchObject?> so, IList<TSortBy> sortBy, TIncludes? includes = null, PagingInfo? pagingInfo = null, CancellationToken token = default)
// Count with custom (nullable) SearchObject
Task<long> Count(TSearchObject? so, CancellationToken token = default)
// Count with multiple SearchObjects
Task<long> Count(IList<TSearchObject?> so, CancellationToken token = default)
Paging at the service layer:
Listonly pages when you pass aPagingInfowith a positivePageSize; otherwise it returns the full set. The configurable default/maximum page size (DefaultPageSize/MaxPageSize, or per-entitye.SetPageSize(...)) is applied by the list and search requests the endpoints send (Entity Operations), not here — so direct service calls keep full control. See Web Endpoints → Paging.
Add, Modify, Save, Remove) do NOT automatically persist changesSaveChanges() to commit all changes to the databaseSaveChanges() the EF change tracker is cleared — all entities saved in that call are now detached. To update one later, pass it through Modify() or Save() again before the next SaveChanges(). A failed SaveChanges() leaves every entry tracked (stock EF Core semantics), so you can fix or remove the offending entity and retry the same callEntityConstraintException — catch that, not DbUpdateException, around direct SaveChanges() calls (seeding, jobs). Transient faults (deadlocks, timeouts) are not wrapped and still throw DbUpdateException subtypes. See Built-in Features → Constraint ExceptionsEntityConcurrencyException; catch that, not DbUpdateConcurrencyException. See Built-in Features → Concurrency ExceptionsDetails(id) can go straight back into Modify() with its navigations loaded. When a foreign key — on the entity or on a Related() child — was set to another key, Modify() drops the reference navigation still pointing at the stored principal and removes the row from that principal’s loaded collections (it may still be in the graph through another path), so the new key is saved rather than overwritten by EF’s attach fixup; the entity then carries that navigation as null. A Related() child stays with the parent whose collection lists it, whatever its own parent key says; move it through the collections. To clear a relation, set both the foreign key and the navigation to null: an empty key beside a loaded navigation is left to the navigation, which is what a request that sends only the nested object relies onTask Save(TEntity item, CancellationToken token = default) // calls Add() or Modify() internally
Task Add(TEntity item, CancellationToken token = default)
Task<TEntity?> Modify(TEntity item, CancellationToken token = default)
Task Remove(TEntity item, CancellationToken token = default)
// Persist all changes to database
Task<int> SaveChanges(CancellationToken token = default)
Query builders are used to filter, sort entities and include navigation properties.
TSearchObject.Filter((query, so) => ...)SearchObject<TKey> is provided// interface
public interface IFilteredQueryBuilder<TEntity, TKey, in TSearchObject>
where TSearchObject : ISearchObject<TKey>
{
IQueryable<TEntity> Build(IQueryable<TEntity> query, TSearchObject? so);
}
// base class
public abstract class FilteredQueryBuilderBase<TEntity, TKey, TSearchObject> : IFilteredQueryBuilder<TEntity, TKey, TSearchObject>
where TSearchObject : ISearchObject<TKey>
{
public abstract IQueryable<TEntity> Build(IQueryable<TEntity> query, TSearchObject? so);
}
TSearchObject for the Entity who’s Filter is being executedSearchObject<TKey> is provided// interface
public interface IGlobalFilteredQueryBuilder
{
IQueryable<TEntity> Build<TEntity, TKey>(IQueryable<TEntity> query, ISearchObject<TKey>? so);
}
public interface IGlobalFilteredQueryBuilder<TEntity, TKey> : IGlobalFilteredQueryBuilder
{
IQueryable<TEntity> Build(IQueryable<TEntity> query, ISearchObject<TKey>? so);
}
// base class
public abstract class GlobalFilteredQueryBuilderBase<TEntity> : GlobalFilteredQueryBuilderBase<TEntity, int>;
public abstract class GlobalFilteredQueryBuilderBase<TEntity, TKey> : FilteredQueryBuilderBase<TEntity, TKey, ISearchObject<TKey>>,
IGlobalFilteredQueryBuilder<TEntity, TKey>
{
IQueryable<TEntity> IGlobalFilteredQueryBuilder<TEntity, TKey>.Build(IQueryable<TEntity> query, ISearchObject<TKey>? so)
=> Build(query, so);
IQueryable<T> IGlobalFilteredQueryBuilder.Build<T, TK>(IQueryable<T> query, ISearchObject<TK>? so)
// a search object of a foreign key type coerces to null — the filter then applies its
// key-agnostic default (e.g. hide archived rows); it must NOT step aside, or a
// soft-delete/security default would be silently dropped
=> Build(query.Cast<TEntity>(), so as ISearchObject<TKey>).Cast<T>();
}
A search object of a foreign key type coerces to null, so a keyed filter falls back to its key-agnostic
default (e.g. a security filter’s scoping predicate) rather than being dropped. The query builder runs one
variant per filter family, preferring the one whose key type matches the search object; when an entity uses
a non-int key, register the matching variants with AddDefaultGlobalQueryFilters<TKey>() so its typed fields
(Id/Ids) are honoured too. Key-agnostic defaults apply even when only the int variant is registered.
RemoveGlobalQueryFilters() removes every global filter registered before it, the ones UseDefaults() adds among
them, so an application can start over with its own; register those after it with AddGlobalFilterQueryBuilder<>().
The archived filter goes too, so archived rows are listed until one is registered again. It extends
IServiceCollection — the UseEntities<TContext>() builder is one, so it chains there — not
EntityServiceCollectionOptions.
TSortyByEntitySortBy is provided// interface
public interface ISortedQueryBuilder<TEntity, TKey, TSortBy>
where TEntity : IEntity<TKey>
where TSortBy : struct, Enum
{
IQueryable<TEntity> SortBy(IQueryable<TEntity> query, TSortBy? sortBy = null);
}
TIncludesEntityIncludes is provided// interface
public interface IIncludableQueryBuilder<TEntity, TKey, TIncludes>
where TEntity : IEntity<TKey>
where TIncludes : struct, Enum
{
IQueryable<TEntity> AddIncludes(IQueryable<TEntity> query, TIncludes? includes = null);
}
Fill [NotMapped] properties here.
// interface
public interface IEntityProcessor<TEntity, TIncludes>
where TIncludes : struct, Enum
{
Task Process(IList<TEntity> items, TIncludes? includes, CancellationToken token = default);
}
Prepare child collections here, or calculated fields.
// interface
public interface IEntityPrepper<in TEntity> : IEntityPrepper
{
Task Prepare(TEntity modified, TEntity? original, CancellationToken token = default);
}
// base class
public abstract class EntityPrepperBase<TEntity> : IEntityPrepper<TEntity>
{
public abstract Task Prepare(TEntity modified, TEntity? original, CancellationToken token = default);
}
[ServerOwned] on a scalar (or e.ServerOwned(x => x.Code, mint) for the fluent form, which also mints on
create) restores that property from the stored row on update, so a PUT/PATCH that omits it cannot null it.
Enforced by AutoServerOwnedPrepper, registered by UseDefaults(). Being a prepper, it guards the
IEntityService write path only and leaves a workflow service’s raw DbContext write alone. It has no
bypass, so a workflow action saving through IEntityService is restored too — guard such fields with your
own prepper and a scoped “trusted writer” flag instead. See
Built-in features.
e.Related() is the shortcut for synchronizing owned child collections. It registers a RelatedCollectionPrepper that diffs the incoming collection against the stored one before SaveChanges(), marking items as added, modified or removed.
One writer per save path. A collection synchronized with
Related()is owned by the parent. Adding a.For<>()/IEntityService<T>for the same child is allowed — the registrations don’t conflict, sinceRelated()registers only a save-time prepper for the parent — but it is safe only under one condition: the parent’s input DTO must leave the collectionnull.
nullon the parent DTO → the sync is a no-op. It short-circuits before diffing, so the child’s own service is the sole writer. This is the supported way to give an owned child its own read/PATCH endpoints.- Collection present → the parent wins. Its next save re-diffs the collection and silently reverts rows written through the standalone service. Watch the difference between absent and empty:
nulltouches nothing,[]deletes every row — including when the navigation was never eager-loaded, since the prepper loads the rows from the store to diff against.Key-type caveat: deletions only happen when every incoming item has a non-null
Id. Withint/Guidkeys that always holds; with astringkey, one new child carrying a nullIdsuppresses all deletions in that save.Startup validation warns on the pairing because it cannot inspect your DTO shape — see §Validation. If the parent genuinely must send the collection, pick one authority: drop the
.For<>(), or drop theRelated()and load the navigation withInclude()in the query builder.
The signature is Related(navigationExpression, prepareFunc, configure), where both prepareFunc and configure are optional:
prepareFunc — a parent-level prepare callback, invoked with the parent entity.configure — a RelatedEntityBuilder callback for shaping the child collection. Use builder.Related(...) to synchronize a nested sub-collection (recursively, to any depth) and builder.Prepare(...) to run a per-item prepare on each child.For an int-keyed child, every builder infers the type argument, whatever the parent’s key, and takes configure in second position too, so e.Related(x => x.Lines, r => r.ServerOwned(x => x.UnitPrice)) needs no parameter name. A child with another key type takes the two-type-argument form below, which always reads its second argument as prepareFunc, so it names configure:.
// Sync the collection, with an optional parent-level prepare:
e.Related<TRelated, TRelatedKey>(x => x.Collection, parentEntity => { /* ... */ });
// Nest sub-collections or add a per-item prepare via the RelatedEntityBuilder:
e.Related<TRelated, TRelatedKey>(x => x.Collection, configure: builder =>
{
builder.Related(item => item.SubCollection); // sync a nested sub-collection
builder.Prepare(item => item.RecalculateTotals()); // per-item prepare on each TRelated
});
// Combine both — a parent-level prepare alongside the nested configuration:
e.Related<TRelated, TRelatedKey>(x => x.Collection,
parentEntity => { /* parent-level prepare */ },
builder =>
{
builder.Related(item => item.SubCollection);
builder.Prepare(item => item.RecalculateTotals());
});
A validator checks what the input alone cannot tell: the entity as the preppers left it (a total they computed), the
row as stored (Original, or Item on a delete) and other rows (a reference that must exist, a code that must be
unique). The shape of the input — required fields, lengths, formats, ranges — belongs on the input DTO: its
DataAnnotations are checked before the input is mapped, so an invalid request never reaches the preppers
(Entity Operations → Input validation). Code that calls IEntityService directly
skips that check; the validators run on every write path.
Add / Modify / Save after every prepper (the global ones and the Related()
sync included, whatever the registration order), and inside Remove, where no prepper runsEntityInputException<TEntity> of the entity it saves, before the entity is tracked, so the client gets every
error in one 400, DELETE includede.Validate(ctx => …) or e.Validate(async ctx => …), and
e.Validate(async (ctx, db, token) => …) with the DbContext and the write’s cancellation token for its queries. The
write awaits an async delegate, so an error added after an await still refuses itModify whose stored row is not found runs no validator: it answers null (not found)Add or Modify takes back what its preppers marked — the rows a Related() sync added, changed or
deleted — and leaves the item itself untracked, even when the caller tracked it. A prepper’s plain edit to another
row the scope already tracked stays, since EF notices it only at SaveChanges()Person also runs when a Person is saved through the
Party service, and the exception is still the service’s own EntityInputException<Party>For<>()
checks every entity implementing it, so register such a validator once, with options.AddValidator<T>(); a class
registered twice runs onceDbContext skips row security: global filters (tenant, owner) scope the entity services’
reads, not db, so db.Customers.AnyAsync(…) accepts another tenant’s CustomerId and its 400 tells the client
that id exists. Where reads are scoped, check the reference through the filtered read service — a class validator
taking IEntityReadService<Customer, int> and refusing when await customers.Details(id, token) is null — or
repeat the scope’s predicate in the query. A validator never takes IEntityService<>: its write service imports
every validator, so the container meets a circular dependency and no entity service in the app resolvesdb track nothing while the validators run, Find / FindAsync included, so a uniqueness check that
returns the row being written — db.Orders.FirstOrDefaultAsync(o => o.Code == ctx.Item.Code, token) on a PUT
that keeps its code — leaves the write free to track its own instance. Only an explicit AsTracking() opts back
in, and the write then throws because another instance with the same key is trackedRelated() sync writes — check Lines from the Order validator, with keys like Lines[0].QuantityItem, Original (the stored row on Modify), Operation (Add / Modify / Remove;
a soft delete of an IArchivable is a Remove) and the Errors added so far; AddError(key, message) takes the property path, "" for the whole entityValueTooLarge) — the Regira front-end shows the translation when it has one and the message as is otherwise.
AddError(key, message, args) adds the values a translation fills in — an anonymous object, new { max = 20 }, or
a dictionary; they go out in the 400’s errorDetails, scalar values onlyRemove, Item is the row as stored — the caller’s instance when none is found — so a delete by key,
Remove(new Order { Id = id }), is judged by the row’s statectx.Item is the instance that gets saved, so a value a validator sets is still
written; changing the entity is a prepper’s job. A primer runs later, on SaveChanges(), so a value a primer
stamps is not there yetIEnumerable<IEntityValidator> to the EntityWriteService constructor (the
constructor without it runs no validators); a service over another store calls
validators.ValidateItem(item, original, operation) itself — for a delete, with the stored row — and
validators.AnyApplyTo(item.GetType()) tells whether any of them can refuse the write. Startup validation warns
about a write path that cannot run themRemove that skips base.Remove skips the validators; mark extra rows for a delete in an override
of RemoveItem, which runs once the validators passedIEntity, say — implements ISelectiveEntityValidator and its
Covers(entityType), so it runs only for the types it covers and startup validation counts it only for thoseEntityValidatorContext<TEntity>(operation, item, original): run Validate on it
and read its ErrorsAbstractValidator rules run in this stage through the FluentValidation adapter| Scope | Runs for |
|---|---|
EntityValidatorBase<Order> |
Order only |
EntityValidatorBase<Party> |
Person and Organization, whichever service saves them |
EntityValidatorBase<IArchivable> |
every entity implementing IArchivable |
// interface
public interface IEntityValidator<in TScope> : IEntityValidator
{
Task Validate(IEntityValidatorContext<TScope> context, CancellationToken token = default);
}
// base class
public abstract class EntityValidatorBase<TScope> : IEntityValidator<TScope>
where TScope : class
{
public virtual bool CanValidate(TScope item) => true;
public abstract Task Validate(IEntityValidatorContext<TScope> context, CancellationToken token = default);
}
.For<Order>(e =>
{
// the row as stored: on a delete, Item is the stored row
e.Validate(ctx =>
{
if (ctx.Operation == EntityWriteOperation.Remove && ctx.Item.Status == OrderStatus.Shipped)
ctx.AddError(nameof(Order.Status), "A shipped order cannot be deleted.");
});
// other rows
e.Validate(async (ctx, db, token) =>
{
// db skips row security; on net10.0 the archived filter still applies. With scoped reads (tenants, owners), check through the filtered read service (above)
if (ctx.Operation != EntityWriteOperation.Remove && !await db.Customers.AnyAsync(c => c.Id == ctx.Item.CustomerId, token))
ctx.AddError(nameof(Order.CustomerId), $"Customer {ctx.Item.CustomerId} does not exist.");
});
// a value a prepper computed
e.AddValidator<CreditLimitValidator>();
})
// a class validator takes its services from DI
public class CreditLimitValidator(AppDbContext db) : EntityValidatorBase<Order>
{
public override async Task Validate(IEntityValidatorContext<Order> ctx, CancellationToken token = default)
{
if (ctx.Operation == EntityWriteOperation.Remove)
return;
var limit = await db.Customers
.Where(c => c.Id == ctx.Item.CustomerId)
.Select(c => c.CreditLimit)
.FirstOrDefaultAsync(token);
// Total is summed from the lines by a prepper, so it is known at this stage and not before
if (ctx.Item.Total > limit)
ctx.AddError(nameof(Order.Total), "ValueTooLarge", new { max = limit });
}
}
using Regira.Entities.DependencyInjection.Validators; // AddValidator on the options and on IServiceCollection
// global: one validator for every entity implementing the interface
services.UseEntities<AppDbContext>(o =>
{
o.AddValidator<ArchivedIsReadOnlyValidator>();
// or a delegate: o.AddValidator<IArchivable>(ctx => …) or async ctx => …,
// and async (ctx, db, token) => … with AddValidator<AppDbContext, IArchivable>
});
// the same overloads extend IServiceCollection, for a registration outside UseEntities()
services.AddValidator<ArchivedIsReadOnlyValidator>();
// the row as stored decides: an archived row takes no edits until it is restored
public class ArchivedIsReadOnlyValidator : EntityValidatorBase<IArchivable>
{
public override Task Validate(IEntityValidatorContext<IArchivable> ctx, CancellationToken token = default)
{
// a restore sets IsArchived back to false, and passes
if (ctx.Operation == EntityWriteOperation.Modify && ctx.Original?.IsArchived == true && ctx.Item.IsArchived)
ctx.AddError("", "An archived record is read-only. Restore it first.");
return Task.CompletedTask;
}
}
SaveChangesInterceptor when the DbContext savesSaveChanges() and SaveChangesAsync(). On the synchronous call a primer that awaits is waited on
without the caller’s synchronization context — its own awaits do not deadlock the caller, but it holds the calling thread for its I/O, so
prefer SaveChangesAsync() when primers do I/OUseEntities(e => e.UseDefaults());
without UseDefaults(), select it with e.WireDbContext(DbContextWiring.PrimerInterceptors)HasCreatedDbPrimer, HasLastModifiedDbPrimer) write UTC values by default; the
auto-wired UTC date convention (UseDefaults()) makes dates read from the database materialize as
DateTimeKind.Utc and serialize to JSON with the Z suffix; ConfigureDefaultJsonOptions() reads
request-body DateTime properties as UTC too, so a prepper sees both sides on one clock (standalone EF: .AddUtcDateTimeConvention() /
SetUtcDateTimeConvention() — Regira.DAL.EFcore.Extensions). Disable UTC handling with
UseEntities(e => e.UseUtc(false)) → local time, values used as given; the convention’s converter follows
the same policy (one process-wide decision: Regira.Utilities.DateTimeDefaults.UseUtc, on by default)// interface
public interface IEntityPrimer<in T>
{
Task PrepareAsync(T entity, EntityEntry entry, CancellationToken token = default);
bool CanPrepare(T entity);
}
// base class
public abstract class EntityPrimerBase<T> : IEntityPrimer<T>
{
public virtual async Task PrepareManyAsync(IList<EntityEntry> entries, CancellationToken token = default)
public abstract Task PrepareAsync(T entity, EntityEntry entry, CancellationToken token = default);
public virtual bool CanPrepare(T? entity) => entity != null;
}
Commit() for the saves inside an explicit
BeginTransaction() — also for contexts sharing that transaction through UseTransaction, whichever of them
commits it — and when an ambient TransactionScope completes. A failed save, a rollback, or a transaction
disposed without committing reacts to nothingIEntityService.SaveChanges(),
the related rows a prepper changes, an attachment upload — flushes in a single SaveChanges, which EF wraps in a
transaction of its own. A unit of work that spans several saves or several services is the application’s:
BeginTransaction() inside CreateExecutionStrategy().Execute(...), or a TransactionScope with
TransactionScopeAsyncFlowOption.Enabled. The library joins either, and its reactors wait for that commitAttachmentFileReactor doesDbTransaction itself — its reactions never run. A
transaction begun outside EF and handed to UseTransaction is known to have ended only when it commits or rolls
back through EF: on Npgsql, which reuses the transaction object of a pooled connection, one disposed without either
leaves its reactions to the next such transaction on that connectionIEntityChange<TEntity>: Kind (Added/Modified/Deleted — a soft delete is Modified),
Entity (the committed row, generated keys filled in), Original (the row as stored before the save) and
ChangedProperties, with the HasChanged(x => x.Status) and ChangedTo(x => x.Status, value) helpers. Values
are detached snapshots without navigationsExecuteUpdate /
ExecuteDelete bypass the change tracker, so no reactor sees themSaveChanges() for a save that
commits on its own; Commit() / CommitAsync() for the saves inside BeginTransaction(), whose own
SaveChanges() returns before anything reacts; the Dispose() that ends a completed TransactionScope, which
runs them synchronouslyDbContext — a reactor that writes saves its
own unit of work, and that save runs the reactors of what it wrote (up to 8 levels deep). Hand slow work to a job
systemUseEntities(e => e.UseDefaults()); without UseDefaults(), add
DbContextWiring.Reactors to e.WireDbContext(...)options.AddReactor<T>() — a reactor on an interface or base type reaches every entity it covers) or per entity (e.AddReactor<T>() — that entity only, whatever type the reactor is written against)services.UseEntities<MyDbContext>(e => e.UseDefaults())
.For<Order>(e =>
{
// inline: the second argument is the reaction's own scoped service provider
e.React(x => x.Status, OrderStatus.Shipped, (change, services, token) =>
services.GetRequiredService<IOrderMailer>().SendShipped(change.Entity.Id, token));
// class-based
e.AddReactor<OrderInvoicingReactor>();
});
public class OrderInvoicingReactor(IOrderInvoicer invoicer) : EntityReactorBase<Order>
{
public override bool CanReact(IEntityChange<Order> change) => change.ChangedTo(x => x.Status, OrderStatus.Delivered);
public override Task React(IEntityChange<Order> change, CancellationToken token = default)
=> invoicer.CreateFor(change.Entity.Id, token); // IOrderInvoicer: the app's own service
}
Every helper service registers per entity, on the For<>() builder; most also register globally, on the
UseEntities() options, where one written against an interface or base type reaches every entity it covers:
| Helper | Global (options.…) |
Per entity (e.…) |
|---|---|---|
| Filter query builder | AddGlobalFilterQueryBuilder<T>() |
Filter(...), AddFilter<T>() |
| Sort / include query builder | — | SortBy(...), Includes(...), AddSortBy<T>(), AddIncludes<T>() |
| Processor | — | Process(...), AddProcessor<T>() |
| Prepper | AddPrepper<T>(), AddPrepper<TScope>(item => …) |
Prepare(...), AddPrepper<T>(), Related(...), ServerOwned(...) |
| Validator | AddValidator<T>(), AddValidator<TScope>(ctx => …) |
Validate(...), AddValidator<T>() |
| Primer | AddPrimer<T>() |
AddPrimer<T>() |
| Normalizer | AddNormalizer<T>() |
AddNormalizer<T>() |
| Reactor | AddReactor<T>() |
React(...), AddReactor<T>() |
| AfterMapper | AddAfterMapper<T>(), AfterMap<TSource, TTarget>(...) |
UseMapping<TDto, TInputDto>().After(...), .AfterInput(...) |
This example uses each of them:
// Configure DbContext — only the provider; UseEntities(e => e.UseDefaults()) wires the interceptors
services.AddDbContext<MyDbContext>(db =>
{
db.UseSqlServer(connectionString);
});
// Configure Entity Services with all helper services
services
.UseEntities<MyDbContext>(options =>
{
// the interceptors, and the built-in filters, preppers, primers and normalizers
options.UseDefaults();
options.UseMapsterMapping();
// Global helper services (apply to every entity implementing an interface or base type)
options.AddGlobalFilterQueryBuilder<TenantQueryFilter>(); // row scoping for every ITenantOwned entity
// using Prepper shortcut (inline implementation)
options.AddPrepper<IHasAggregateKey>(x => x.AggregateKey ??= Guid.NewGuid());
options.AddValidator<ArchivedIsReadOnlyValidator>(); // see Entity Validators
options.AddPrimer<HasCreatedByPrimer>(); // stamps the user on every IHasCreatedBy
options.AddReactor<AuditTrailReactor>(); // an EntityReactorBase<IEntity>: every committed change
})
// Category
.For<Category, Guid>(e =>
{
// Query Filter
e.AddFilter<CategoryQueryFilter>();
// Sorting — a simple entity takes one fixed order; the request's ?sortBy= is honored only on complex entities
e.SortBy(query => query.OrderBy(x => x.Name));
// Processor
e.AddProcessor<CategoryProcessor>();
})
// Product
.For<Product, ProductSearchObject, ProductSortBy, ProductIncludes>(e =>
{
// Query Filter (inline)
e.Filter((query, so) =>
{
// filtering on Id is implemented by global filter
if (so?.MinPrice != null)
query = query.Where(x => x.Price >= so.MinPrice);
if (so?.MaxPrice != null)
query = query.Where(x => x.Price <= so.MaxPrice);
return query;
});
// Sorting
e.SortBy((query, sortBy) =>
{
return sortBy switch
{
ProductSortBy.Name => query.OrderBy(x => x.Name),
ProductSortBy.NameDesc => query.OrderByDescending(x => x.Name),
ProductSortBy.Price => query.OrderBy(x => x.Price),
ProductSortBy.PriceDesc => query.OrderByDescending(x => x.Price),
_ => query.OrderBy(x => x.Id)
};
});
// Include — one registration per entity (a second call replaces the first).
// Order inside an include when the relation carries sorted rows. Archived rows need no
// predicate here on net10.0: the archived filter is an EF query filter, so it also
// applies inside Include(...) — see Built-in features > Soft delete for the net8.0 gap.
e.Includes((query, includes) =>
{
if (includes?.HasFlag(ProductIncludes.Category) == true)
query = query.Include(x => x.Category);
if (includes?.HasFlag(ProductIncludes.Reviews) == true)
query = query.Include(x => x.Reviews!.OrderBy(r => r.SortOrder));
return query;
});
// Processor
e.Process((items, includes) =>
{
foreach (var item in items)
{
// Calculate display properties
item.DisplayPrice = $"${item.Price:F2}";
}
return Task.CompletedTask;
});
// Prepper
e.Prepare(item =>
{
// Ensure SKU is set
item.Sku ??= GenerateSku(item);
});
// Primer
e.AddPrimer<ProductPrimer>();
// Related entities — simple: just sync the collection
e.Related(x => x.Reviews);
})
// Order
.For<Order, int, OrderSearchObject, OrderSortBy, OrderIncludes>(e =>
{
e.AddFilter<OrderQueryFilter>();
// OrderOrThenBy / OrderOrThenByDescending (Regira.Entities.EFcore.Extensions) start the
// ordering or continue it with ThenBy — the lambda is called once per requested sort value
e.SortBy((query, sortBy) => sortBy switch
{
OrderSortBy.OrderNumber => query.OrderOrThenBy(x => x.OrderNumber),
OrderSortBy.OrderDate => query.OrderOrThenBy(x => x.OrderDate),
OrderSortBy.TotalAmount => query.OrderOrThenBy(x => x.TotalAmount),
_ => query.OrderOrThenByDescending(x => x.OrderDate)
});
e.AddIncludes<OrderIncludableQueryBuilder>();
e.AddProcessor<OrderProcessor>();
// Complex prepper with DbContext
e.Prepare(async (item, dbContext) =>
{
// Recalculate order totals
item.TotalAmount = item.OrderItems?.Sum(x => x.Quantity * x.UnitPrice) ?? 0;
await Task.CompletedTask;
});
// Server-owned field — restored from the stored row on update, minted on create
e.ServerOwned(x => x.OrderNumber, _ => $"ORD-{Guid.NewGuid():N}"[..16]);
// Simple related with parent-level prepare
e.Related(x => x.OrderItems, item => item.OrderItems?.SetSortOrder());
// Configure overload — nest sub-collections or add per-item prepare
// e.Related(x => x.OrderItems, builder =>
// {
// builder.Related(oi => oi.Options);
// builder.Prepare(oi => oi.RecalculateTotals());
// });
// Validators — run after every prepper, so they see the recalculated total
e.Validate(ctx =>
{
if (ctx.Operation == EntityWriteOperation.Remove && ctx.Item.Status == OrderStatus.Shipped)
ctx.AddError(nameof(Order.Status), "A shipped order cannot be deleted.");
});
e.AddValidator<CreditLimitValidator>();
// Normalizer — runs inside SaveChanges, after the primers
e.AddNormalizer<OrderNormalizer>();
// Reactors — run once the save is committed
e.React(x => x.Status, OrderStatus.Shipped, (change, services, token) =>
services.GetRequiredService<IOrderMailer>().SendShipped(change.Entity.Id, token));
e.AddReactor<OrderInvoicingReactor>();
// Mapping + AfterMapper — UseMapping returns the mapping builder, so it goes last
e.UseMapping<OrderDto, OrderInputDto>()
.After((order, dto) => dto.LineCount = order.OrderItems?.Count ?? 0);
});
Registration Order Matters
EntityServiceCollectionOptions)A rule that belongs to one stage — a filter, a prepper, a validator — is a helper service. The service itself is replaced for what has no stage: methods of its own, a concern around every call, another data source.
| Registration | The class | Registered as |
|---|---|---|
e.HasRepository<T>() |
derives from EntityRepository — overrides members, adds methods |
the entity’s IEntityRepository<…> and IEntityService<…> |
e.UseEntityService<T>() |
derives from EntityWrappingServiceBase and wraps the repository, or implements IEntityService<…> over another store |
the entity’s IEntityService<…> |
flowchart LR
caller["Endpoints · jobs"] --> svc["IEntityService"]
svc -- UseEntityService --> wrapper["ProductService<br/>wraps"]
svc -. no wrapper .-> repo["IEntityRepository"]
wrapper --> repo
repo -- HasRepository --> custom["ProductRepository<br/>derives from EntityRepository"]
repo -. default .-> def["EntityRepository"]
custom --> rw["Read and write services"]
def --> rw
using Microsoft.Extensions.Logging;
using Regira.Entities.EFcore.Services;
public class Product : IEntityWithSerial
{
public int Id { get; set; }
public string? Title { get; set; }
public bool IsFeatured { get; set; }
}
public record ProductSearchObject : SearchObject
{
public bool? IsFeatured { get; set; }
}
// HasRepository: a method of its own beside the standard ones
public interface IProductRepository : IEntityRepository<Product, int, ProductSearchObject>
{
Task<IList<Product>> ListFeatured(CancellationToken token = default);
}
public class ProductRepository(
IEntityReadService<Product, int, ProductSearchObject> readService,
IEntityWriteService<Product, int> writeService)
: EntityRepository<Product, int, ProductSearchObject>(readService, writeService), IProductRepository
{
// through the read pipeline, so the global filters (row security) and the entity's filters apply
public Task<IList<Product>> ListFeatured(CancellationToken token = default)
=> List(new ProductSearchObject { IsFeatured = true }, null, token);
}
// UseEntityService: behaviour around a call, the repository left as it is
public class ProductService(IEntityRepository<Product, int, ProductSearchObject> repository, ILogger<ProductService> logger)
: EntityWrappingServiceBase<Product, int, ProductSearchObject>(repository)
{
public override async Task Remove(Product item, CancellationToken token = default)
{
logger.LogInformation("Removing product {Id}", item.Id);
await base.Remove(item, token);
}
}
services.UseEntities<ShopDbContext>(o => o.UseDefaults())
.For<Product, int, ProductSearchObject>(e =>
{
e.Filter((query, so) => so?.IsFeatured is { } featured ? query.Where(x => x.IsFeatured == featured) : query);
e.HasRepository<ProductRepository>();
e.AddTransient<IProductRepository, ProductRepository>(); // inject it by its own interface
e.UseEntityService<ProductService>(); // after HasRepository: the last IEntityService registration wins
});
IEntityRepository<…>, never IEntityService<…>: that resolves to the
wrapper itself, and the container meets a circular dependencyIEntityService<…>, and the last one wins — so HasRepository goes before
UseEntityService, or the repository replaces the wrapperSave routes to the wrapper’s own Add or Modify, so logic around a create or an update goes there; the
members a wrapper can override are listed under Built-in Features → Wrapping serviceDetails(id) on an IArchivable entity overrides Details(id, archived) too: a read with
?archived= and the re-read after a save go through the secondIEntityService<…> of its
own, registered with UseEntityService; it runs no preppers or validators unless it calls them (see
Entity Validators)options.UseRepository(...) swaps the default EntityRepository for your own generic repository in every
For<>() that does not name one itself (e.HasRepository<T>() and e.UseEntityService<T>() still win).
Pass the classes unbound; each is matched to a For<>() by its number of type parameters, the same as the
EntityRepository it derives from — AppRepository<TEntity> serves For<TEntity>(), AppRepository<TEntity, TKey>
serves For<TEntity, TKey>(), and so on up to the five-parameter complex shape.
using Regira.Entities.EFcore.Services;
public class AppRepository<TEntity, TKey>(
IEntityReadService<TEntity, TKey, SearchObject<TKey>> readService,
IEntityWriteService<TEntity, TKey> writeService)
: EntityRepository<TEntity, TKey>(readService, writeService)
where TEntity : class, IEntity<TKey>
{
public override Task Save(TEntity item, CancellationToken token = default)
{
// behaviour shared by every entity
return base.Save(item, token);
}
}
// For<TEntity>() with an int key
public class AppRepository<TEntity>(
IEntityReadService<TEntity, int, SearchObject<int>> readService,
IEntityWriteService<TEntity, int> writeService)
: AppRepository<TEntity, int>(readService, writeService), IEntityRepository<TEntity>
where TEntity : class, IEntity<int>;
services
.UseEntities<MyDbContext>(options =>
{
options.UseDefaults();
options.UseRepository(typeof(AppRepository<>), typeof(AppRepository<,>));
})
.For<Product>() // AppRepository<Product>
.For<Category, Guid>(); // AppRepository<Category, Guid>
To see every read and write — logging, timing, auditing — override every member the repository has: Add,
Modify, Save, Remove and SaveChanges; both Details overloads; List and Count with the search object
and with an object, which the generated controllers use to look a row up before a save or a delete; and, on the
complex shapes, List and Count with a list of search objects. Each member hands its call straight to the read or
write service, so one call reaches one member. The exception is Details(id, archived): it returns Details(id)
when the filter changes nothing — none given, or an entity that is not IArchivable — so log there only when it does
not hand over. Save never passes through Add or Modify. Keep the shared logic in one class that each shape’s
repository calls.
A For<>() whose shape has no matching class keeps the default EntityRepository, and the startup validation
logs a warning naming those entities. A class that cannot serve an entity — a type constraint the entity does
not meet, or a missing interface of the EntityRepository it replaces — throws at that For<>().
Tip:
// Use extension methods to configure Entities.
// Take the interface as the 'this' parameter; return the concrete EntityServiceCollection<TContext>
// (every For<>() returns it, and only it implements IServiceCollection — chains stay composable).
public static class ProductServiceCollectionExtensions
{
public static EntityServiceCollection<TContext> AddProducts<TContext>(this IEntityServiceCollection<TContext> services)
where TContext : DbContext
=> services.For<Product>(e =>
{
// put logic here ...
});
}
// Resulting:
services
.UseEntities<MyDbContext>(/* ... */)
.AddProducts()
.AddCategories()
.AddOrders();