Regira-Packages

Entity Services

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>

Service Layer Architecture

flowchart 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.

Read and save flow

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.

Standard EntityRepository Methods

Read Operations

// 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: List only pages when you pass a PagingInfo with a positive PageSize; otherwise it returns the full set. The configurable default/maximum page size (DefaultPageSize / MaxPageSize, or per-entity e.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.

Write Operations

Task 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)

Repository helper services

Query Builders

Query builders are used to filter, sort entities and include navigation properties.

Filter Query Builders

// 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);
}

Global Filter Query Builders

// 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.

Sort Query Builder

// interface
public interface ISortedQueryBuilder<TEntity, TKey, TSortBy>
    where TEntity : IEntity<TKey>
    where TSortBy : struct, Enum
{
    IQueryable<TEntity> SortBy(IQueryable<TEntity> query, TSortBy? sortBy = null);
}

Include Query Builder

// interface
public interface IIncludableQueryBuilder<TEntity, TKey, TIncludes>
    where TEntity : IEntity<TKey>
    where TIncludes : struct, Enum
{
    IQueryable<TEntity> AddIncludes(IQueryable<TEntity> query, TIncludes? includes = null);
}

Entity Processors

Fill [NotMapped] properties here.

// interface
public interface IEntityProcessor<TEntity, TIncludes>
    where TIncludes : struct, Enum
{
    Task Process(IList<TEntity> items, TIncludes? includes, CancellationToken token = default);
}

Entity Preppers

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);
}

Server-owned fields

[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, since Related() 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 collection null.

Key-type caveat: deletions only happen when every incoming item has a non-null Id. With int/Guid keys that always holds; with a string key, one new child carrying a null Id suppresses 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 the Related() and load the navigation with Include() in the query builder.

The signature is Related(navigationExpression, prepareFunc, configure), where both prepareFunc and configure are optional:

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());
    });

Entity Validators

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.

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;
    }
}

Entity Primers

// 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;
}

Entity Reactors

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
}

Dependency Injection

Configuration Example

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

  1. Global services execute first (registered on EntityServiceCollectionOptions)
  2. Entity-specific services execute next (registered on entity builder)

Replacing the repository for one entity

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
    });

Replacing the repository app-wide

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();

Overview

  1. Index — Overview of Regira Entities
  2. Entity Models — Creating and structuring entity models
  3. Services — Implementing entity services, repositories and the write pipeline
  4. Mapping — Mapping Entities to and from DTOs
  5. Web Endpoints — Exposing entity operations as HTTP endpoints
  6. Normalizing — Data normalization techniques
  7. Attachments — Managing file attachments
  8. Built-in Features — Ready to use components
  9. Checklist — Step-by-step guide for common tasks
  10. Practical Examples — Complete implementation examples