PANiXiDA.Core.Backend.CodeGenerator
1.0.2
dotnet add package PANiXiDA.Core.Backend.CodeGenerator --version 1.0.2
NuGet\Install-Package PANiXiDA.Core.Backend.CodeGenerator -Version 1.0.2
<PackageReference Include="PANiXiDA.Core.Backend.CodeGenerator" Version="1.0.2" />
<PackageVersion Include="PANiXiDA.Core.Backend.CodeGenerator" Version="1.0.2" />
<PackageReference Include="PANiXiDA.Core.Backend.CodeGenerator" />
paket add PANiXiDA.Core.Backend.CodeGenerator --version 1.0.2
#r "nuget: PANiXiDA.Core.Backend.CodeGenerator, 1.0.2"
#:package PANiXiDA.Core.Backend.CodeGenerator@1.0.2
#addin nuget:?package=PANiXiDA.Core.Backend.CodeGenerator&version=1.0.2
#tool nuget:?package=PANiXiDA.Core.Backend.CodeGenerator&version=1.0.2
PANiXiDA.Core.Backend.CodeGenerator
PANiXiDA.Core.Backend.CodeGenerator is a .NET library that scaffolds editable C# CRUD files from domain aggregates and their child entity collections.
Status
Features
- Generates C# commands, queries, handlers, validation, EF Core mappings, and ASP.NET Core endpoints.
- Supports explicitly configured child entity collections with parent-scoped mutations and paginated queries.
- Maps scalar properties, enumerations, single-value objects, and compound value objects from the domain model.
- Ships Scriban templates and shared partials inside the library. Jobs can replace individual templates and output directories.
- Supports multiple jobs, selected artifacts, explicit overwrite, and deletion of existing files at the selected output paths.
Requirements
- .NET 10 SDK.
- A backend repository with PANiXiDA.Core domain conventions and the corresponding Application, Infrastructure, and Presentation projects for the artifacts you select.
Installation
Add the generator and JSON configuration provider to the console project in tools.
dotnet add tools/Acme.Store.CodeGenerator package PANiXiDA.Core.Backend.CodeGenerator
dotnet add tools/Acme.Store.CodeGenerator package Microsoft.Extensions.Configuration.Json --version 10.0.14
Quick Start
From the backend repository root, run the console project after adding this code to its Program.cs.
using Microsoft.Extensions.Configuration;
using PANiXiDA.Core.Backend.CodeGenerator;
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
var changes = await BackendCodeGenerator.GenerateAsync(configuration);
foreach (var change in changes)
{
Console.WriteLine($"{change.Action}: {change.Path}");
}
Save the JSON configuration alongside the console project and copy it to the build output.
<ItemGroup>
<None Update="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
The console project loads its own JSON file. The library reads jobs from the supplied IConfiguration and uses the current working directory as the backend repository root. Pass repositoryRoot explicitly when launching the tool from another directory.
{
"jobs": [
{
"pathToModels": "src/Modules/Catalog/Acme.Store.Catalog.Domain",
"models": [
{
"aggregate": "Acme.Store.Catalog.Domain.Products.Product",
"route": "products",
"detailsFields": ["Id", "Name"],
"listFields": ["Id", "Name"]
}
],
"generatedFiles": ["CreateCommand", "UpdateCommand"],
"overwriteExisting": false,
"deleteGenerated": false
}
]
}
dotnet run --project tools/Acme.Store.CodeGenerator
The example generates two files. See the full CRUD example for the full artifact list and a children entry.
Model Conventions
- An aggregate derives from
AggregateRoot<TId>and has a Guid-backed ID exposingValueandCreate(Guid). It provides a staticCreatereturningResult<TAggregate>and an instanceUpdatereturningResult. - Method parameters bind to writable properties by name and input type. A private setter is supported. Use the domain types in aggregate and child methods. The generated handlers bind scalar request values to identifiers, enumerations, and value objects through their factories. For a compound value object, each factory parameter must match a readable scalar property by name, type, and nullability.
- Create and update handlers call the value object factories and combine their errors with
Result.Combinebefore invoking the aggregate. An optional value object requires aCreateoverload accepting the nullable value or all nullable components. The factory determines the result for missing input. - Generated Create, Update, and Delete command handlers implement
IRequireTransaction. - Create and update commands and HTTP requests flatten compound value objects into primitive fields. Components use their own names, such as
AmountandCurrency. When a name conflicts with another field or an identifier, the generator prefixes it with the domain property name. Mapperly maps the request fields to the command by name. - Both read projections include
Id. Compound value objects map to one column per component through EF Core 10 complex properties, including on child entities. EF infers the optionality of the whole complex property from its CLR type and nullable reference annotations. The generated configuration sets the optionality of each component explicitly. ConfigureUseSnakeCaseNamingConvention()on both DbContexts so write properties and flat read properties such asListPriceAmountmap to the same columns. An optional complex property needs at least one non-nullable component to distinguish an absent object. Give entities an EF-bindable constructor whose parameters do not include complex properties. - Built-in child persistence requires a public non-nullable CLR property of the aggregate's ID type on the child. With multiple matches, the generator selects the property named after the ID type, such as
ProductVariant.ProductId. Initialize that property when the aggregate creates the child. Both EF models use it as the foreign key and useIdas the primary key. Child IDs must be unique across the entire child table. Configurationconfigures the aggregate collection withHasMany, cascade deletion andAutoIncludefor child configurations planned in any job or already present at their configured paths.ChildConfigurationconfigures the child entity, its key and value objects. Regenerate both artifacts to move a relationship out of an older generated child configuration.- A child collection exposes entities deriving from
Entity<TId>. Configurecollection,route, read projections, and the aggregate method names for the write artifacts you select. The element type supplies the name for generated child types and files. Theroutesetting supplies the child URL segment. Create returnsResult<TChildId>. Update and delete take the child ID first and returnResult. - Child write handlers combine ID and value object validation before loading the parent. The aggregate's update and delete methods check whether the child exists. The handlers call the aggregate repository's
Updateafter a successful mutation.
For existing generated Create and Update operations, regenerate the commands, validators, handlers, requests, and mappers together. Clients should send compound components directly in the JSON body, for example {"amount": 20, "currency": "USD"}.
Configuration
| Setting | Behavior |
|---|---|
pathToModels |
Path to the Domain project directory or its .Domain.csproj, relative to the backend repository root. |
models |
One or more aggregate configurations from that Domain project. |
generatedFiles |
Explicit artifact names. Use Child* artifacts for entries in children. |
templates |
Optional mapping from an artifact name or an embedded partial filename to a Scriban file within the repository. Relative paths are resolved from templateBaseDirectory, which defaults to the repository root when passing IConfiguration. |
outputDirectory |
Optional mapping from an artifact name to a directory relative to the repository root. Supports {Module}, {ModuleName}, {Feature}, and {Resource}. |
overwriteExisting |
Allows replacing selected files. Defaults to false. |
deleteGenerated |
Deletes existing files at the selected output paths. Defaults to false. |
deleteGenerated uses the file names and directories resolved from the job, including outputDirectory overrides. It also deletes manually edited files at those paths and skips missing files. Jobs that select child artifacts build Domain to resolve their entity names. Jobs that select only aggregate artifacts use the configured aggregate name.
For example, "templates": { "CreateCommand": "Templates/MyCreate.sbn", "DtoRecord.sbn": "Templates/MyDto.sbn" } overrides one artifact and one shared partial for the job. All other templates come from the package. Pass templateBaseDirectory: "tools/Acme.Store.CodeGenerator" to resolve the example overrides next to the tool project. The overload that takes a JSON path resolves relative overrides from that file's directory.
Overrides of LoadParent.sbn receive an already validated parentIdResult and use model.aggregate_variable for the loaded aggregate's local variable.
Overrides of BindDomainValues.sbn include the result variables from id_results in Result.Combine.
Override DetailsMapper, GetListMapper, ChildDetailsMapper, or ChildGetListMapper to customize ToResponse. Remove any ReadResponseMapping.sbn override from existing jobs.
Generated Create and Update handlers, write repositories, and EF configurations use the aggregate's short type name when it resolves unambiguously. They use DomainAggregate for known collisions, such as a Product type inside a module named Organization.Product.Module or a File type that conflicts with an SDK implicit using. EF configurations use normal imports for unique value object and enumeration names and type aliases for collisions. A child configuration resolves the parent aggregate alongside the child types and aliases the conflicting references. The Repository and Configuration templates can be overridden for additional project-specific imports.
Built-in templates place using directives above the file-scoped namespace. Write configurations also resolve collisions with the types imported by the EF Core 10 and Npgsql namespaces used by the backend template. The generated write configuration names selector parameters after their domain entities and value object properties. Scalar value object conversions infer the provider type from the stored value. Optional properties use IsRequired(required: false), and EF passes null through without calling the conversion lambdas. The EF conversion passes the provider value directly to Create. For a value type it uses Create(T) when available, or Create(T?) when that is the only overload.
When regenerating code that already stores compound value objects in jsonb, add a migration in the consuming project to move existing values into the new columns before removing the old columns.
When replacing a generated child shadow key, migrate the previous parent_id column to the name of the CLR foreign key when the name changes, for example product_id.
When migrating from a composite primary key to id, verify that every ID is unique in the child table before replacing the primary key.
The generated read repository includes each method when its corresponding DetailsReadModel or ListItemReadModel is selected by any job for that resource, or already exists at its default or configured output path. The same rule applies to Child* read artifacts. Select the corresponding mapper and, for list queries, sorting artifact if those files do not already exist.
IReadRepository and ReadRepository generate the aggregate read contract and implementation. Select ChildIReadRepository and ChildReadRepository to generate a separate pair for each configured child collection. Child contracts go under the aggregate's Application Abstractions directory and child implementations go under its Infrastructure Read directory. Both repositories use the module's read context and the inherited Query for their respective database models. Include the corresponding read database models, projections, mappers, and list sorting artifacts.
When upgrading from a unified repository, regenerate the aggregate and child repository contracts and implementations, plus ChildGetDetailsHandler and ChildGetListHandler. Remove any obsolete partial repository files after moving manual changes.
Child read use cases, projections, and mappers live under the aggregate feature. ChildReadDbModel derives from ReadDbModel<Guid> and exposes a reference navigation to the aggregate read model, such as Product. EF uses the inherited Id as the primary key and pairs Product with ProductId by convention. The generator adds [ForeignKey] when the CLR foreign key does not match the navigation convention. Child queries filter by the parent foreign key and, for details, the child ID. Child list handlers use the aggregate read repository to return 404 when the parent is missing, then read the page through the child repository. List repositories apply search, sorting, and pagination in the database.
Details and list read models and HTTP responses are flat positional records. Compound value objects contribute primitive parameters with short component names, prefixed with the domain property name when names collide. Mapperly queryable projections map storage columns from each resource's own read database model. Presentation mappers copy fields by name and preserve nullable components.
When updating an existing scaffold, regenerate the read models, their queryable projections, Presentation responses and mappers together. The detailsFields and listFields settings still refer to domain properties. For features with compound values, this changes the GET response JSON. For example, the listPrice object becomes the top-level amount and currency fields.
The aggregate's ReadDbModel declares child collections as ICollection<T>. It includes child models from the current generation run and configured child model files that already exist. When adding or removing a child collection, regenerate or edit the aggregate read model as well. If an older child model declares the collection in a partial aggregate class, update both generated files together. Non-nullable strings in read database models are initialized with string.Empty.
Read database models group scalar properties (including flattened value objects and foreign keys), primitive collections, reference navigations, and collection navigations in that order. A single blank line separates consecutive nonempty groups. Primitive collections support one-dimensional arrays, List<T>, and the standard generic sequence and list interfaces implemented by List<T>. The generator preserves the collection and element nullability and initializes non-nullable collection properties to an empty collection.
The child read database model uses its domain entity name, so ProductVariantReadDbModel and ProductVariant both map to product_variants by convention. When upgrading an existing configuration, remove children[].resource. If it renamed generated types, replace those files and remove the old read-context configuration call.
Select Filter and FilterValidator to generate the feature's IFilter record and FluentValidation validator under Application/<Feature>/Common/Filters. Use ChildFilter and ChildFilterValidator for a child feature. These artifacts can be generated independently of read operations.
Set searchFields on each aggregate or children entry to choose which properties participate in text search. The names must be unique properties mapped to string or string? on the read side. For example, use ["Name"] for Product and ["Sku"] for its variant collection. listFields controls the list projection, so search can also use properties omitted from the list. An omitted or empty searchFields disables text search and produces an empty filter when that artifact is selected. For existing jobs that used search, set searchFields explicitly before regenerating.
With a filter and search fields configured, select GetRequest or ChildGetRequest for the corresponding list. These artifacts generate request records with an optional Search property that Minimal APIs bind through [AsParameters]. The list mapper maps the request to the query's filter. Before sorting and pagination, the repository uses PostgreSQL ILIKE with %{Search.Trim()}% across the selected fields. Percent signs and underscores follow PostgreSQL pattern matching rules. When enabling or disabling search in generated code, regenerate the filter, request, endpoint, mapper, query, validator, handler, and the corresponding read repository contract and implementation.
Generated endpoint groups require authorization. When selecting DeleteEndpoint or ChildDeleteEndpoint, include the corresponding DeleteMapper or ChildDeleteMapper. Create endpoints use the details route when it exists and return HTTP 201 with the created response otherwise.
Review the generated files before committing them to your backend repository.
Development
dotnet restore
dotnet format --verify-no-changes
dotnet build --configuration Release
dotnet test --configuration Release
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.Configuration.Binder (>= 10.0.14)
- Scriban (>= 7.6.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.2 | 75 | 11/30/2026 |