Skip to content

Latest commit

 

History

History
1339 lines (1144 loc) · 83.1 KB

csharp.md

File metadata and controls

1339 lines (1144 loc) · 83.1 KB

C# port

A first-class full-stack target on .NET 8. Loader + conformance + EF Core codegen

  • render engine + the meta CLI all ship. Targets EF Core + ASP.NET Core + Postgres + Npgsql. The baseline is .NET 8 (net8.0); the tool and the packages are not built for earlier runtimes.

Schema migrations and database checks run in the Node meta tool. dotnet meta generates and verifies code, but writing and applying migrations (npx meta migrate, npx meta migrate apply-pending) and checking a live database against the model (npx meta verify --db) need Node: npm i -D @metaobjectsdev/cli, then npx meta init --config-only to point it at your metadata. Node is needed where migrations are written or applied, not in your running service. What else behaves differently in this port is listed in What differs by language.

Regeneration and hand edits

dotnet meta gen has no three-way merge (that is TypeScript-only). It decides per file from a committed hash manifest, .metaobjects/.gen-state/.hashes/: a file that still matches what the generator wrote is overwritten, and an edited one is refused by name. To change what a generator emits, dotnet meta eject <name> copies it into codegen/generators/ for you to own. Commit the manifest.

Keep your EF Core model: contracts as plain DTOs

Contracts and entities are not forced into one type. Declare an object with no source.rdb (a sourceless object) and EntityGenerator writes a POCO with DataAnnotations and no EF mapping: no [Table], no DbSet<>, no AppDbContext entry, no CRUD routes, no filter allowlist. A sourced entity gets [Table]/[Key]/[Column] and the full EF Core surface. So the same model can hold sourceless request/response contracts that you hand to your own controllers and sourced entities where you want MetaObjects to own the mapping; your existing hand-written EF entities are not touched.

A declaration with no source.rdb (this one is a plain DTO POCO):

{ "object.entity": {
    "name": "AuthorSummary",
    "children": [
      { "field.long":   { "name": "id" } },
      { "field.string": { "name": "name", "@required": true, "@maxLength": 200 } },
      { "identity.primary": { "@fields": "id" } }
    ]
}}

Wire only the generators you want in codegen/Generators.cs; leave db-context out if you keep your own DbContext, since the generated AppDbContext emits Postgres column types (uuid, jsonb, timestamptz) today. Note that the generated CRUD routes use the entity POCO, as described under Use; the DTO shape above is for objects you keep sourceless.

Install

Published to NuGet at 1.2.0 — four packages, version-locked to the C# port version: MetaObjects (loader), MetaObjects.Codegen, MetaObjects.Render and the MetaObjects.Cli tool.

Install the CLI as a .NET tool, then scaffold the generator list:

dotnet tool install --global MetaObjects.Cli
dotnet meta          # bare invocation prints the usage banner
dotnet meta init     # writes codegen/Generators.cs (the generator list), codegen/Program.cs, codegen/Codegen.csproj

Your app is a separate project beside codegen/. dotnet meta init runs from the root of your repository, and the app's .csproj at that root must not compile codegen/, which has its own Main (without the Compile Remove the build fails with CS0579 and CS8802). This sample uses SQLite so it runs with nothing else installed; the same generated code runs on Postgres (see Use):

<!-- App.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <!-- the helpers the generated routes call; before 1.3.0 they were in MetaObjects.Codegen -->
    <PackageReference Include="MetaObjects.AspNetCore" Version="1.3.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.11" />
  </ItemGroup>
  <ItemGroup>
    <Compile Remove="codegen/**" />
  </ItemGroup>
</Project>

The C# CLI is invoked as dotnet meta (command dotnet-meta), or run directly from the repo via dotnet run --project server/csharp/MetaObjects.Cli. It is deliberately not a bare meta executable — that name belongs to the Node meta CLI (TypeScript codegen and the reference migration helper, ADR-0015).

Configure

Drop metadata under metaobjects/, for example metaobjects/meta.blog.json:

{ "metadata.root": {
    "package": "acme::blog",
    "children": [
      { "object.entity": {
        "name": "Author",
        "children": [
          { "source.rdb": { "@table": "authors" } },
          { "field.long":   { "name": "id" } },
          { "field.string": { "name": "name", "@required": true, "@maxLength": 200, "@filterable": true } },
          { "field.string": { "name": "bio", "@maxLength": 2000 } },
          { "field.enum":   { "name": "role", "@values": ["writer", "editor"], "@required": true, "@filterable": true } },
          { "identity.primary": { "@fields": "id", "@generation": "increment" } }
        ]
      }}
    ]
}}

Unknown top-level keys. dotnet meta reads the top level of .metaobjects/config.json and ignores any key the C# port does not model. A key in no port's vocabulary warns on standard error, once per key, with the known keys, in TypeScript's words, and nothing fails: a newer MetaObjects may have written the key. A key inside a block C# owns (csharp, naming, wire and the rest) is refused as before.

Building on a shared model (optional)

A model published from another repository is declared under dependencies in .metaobjects/config.json and synced by the Node CLI (meta deps sync writes .metaobjects/deps.lock.json and a committed snapshot under .metaobjects/deps/). dotnet meta reads both, at every rung of the source ladder, and never writes them: a snapshot that no longer matches the lock fails with ERR_DEPENDENCY_SNAPSHOT_STALE. The snapshot loads first, so your own metadata can extends, overlay or reference its nodes, but an imported node is not generated unless scope.include names its package, and an imported requirement is not counted by the requirement gate unless requirements.inherit names it. What C# does and does not do is in Metadata dependencies.

dotnet meta verify --deps asks whether the publisher has moved since you synced: it re-resolves each dependency's path, reads the publisher's metaobjects.pkg.json, hashes the artifact beside it and compares with the lock. current, drifted and unresolved (no directory, a bad manifest, a hash that does not match, or no lock entry yet) are the same states and the same ERR_DEPENDENCY_UPSTREAM_DRIFT exit as meta deps check. The check runs before the metadata loads, so a dependency not yet synced is reported unresolved first; the load that follows still refuses the missing or stale snapshot with ERR_DEPENDENCY_SNAPSHOT_STALE and exit 2. It never writes anything, it is never part of a bare verify, and an npm, python, maven or nuget dependency is reported unresolved (run the Node meta deps check for those).

Custom providers (optional)

When the project needs a subtype or an attribute the core does not ship, write a public class implementing IMetaDataTypeProvider (with a public parameterless constructor) in its own class library, and list the built assembly in .metaobjects/config.json:

{
  "schema_version": 1,
  "csharp": {
    "providers": [
      { "assembly": "vocabulary/bin/Debug/net8.0/Acme.Vocabulary.dll", "type": "Acme.Vocabulary.AcmeVocabularyProvider" }
    ]
  }
}

assembly is relative to the directory holding .metaobjects/. Build the vocabulary first; a missing dll, a missing type or a type that is not a provider is refused with an error naming csharp.providers. dotnet meta gen and verify --codegen (through the codegen/ runner), dotnet meta verify and dotnet meta fmt then all compose the core providers plus these. An application that loads the model itself composes the registry, and ComposeRegistry takes exactly the set it is given:

var registry = Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new AcmeVocabularyProvider()]);
var load = MetaDataLoader.FromDirectory("./metaobjects", registry, strict: true);

The provider object has the same contract (Id, Dependencies, RegisterTypes(registry) calling Register and Extend) as the other ports. Composition errors surface ERR_PROVIDER_DUPLICATE_ID, ERR_PROVIDER_MISSING_DEPENDENCY and ERR_PROVIDER_DEPENDENCY_CYCLE. If another port's tools load the same metadata, that port needs its own copy of the provider (same id, same vocabulary); a provider registered in one language is invisible to the others. See ../features/extending-with-providers.md for the full reference with a worked AcmeVocabularyProvider, and ../recipes/extending-metaobjects-with-providers.md for a worked example.

Generate

The generator list. Every generator a project runs is an entry in codegen/Generators.cs, with its options as init properties, the api reference included (ADR-0034 Amendment 9). dotnet meta init writes that file with an empty list, beside codegen/Program.cs (two lines that run it) and codegen/Codegen.csproj. dotnet meta gen runs the list through dotnet run --project codegen; nothing is generated that the list does not declare, and a project with no codegen/Generators.cs gets an error, not output.

// codegen/Generators.cs
using MetaObjects.Codegen;

public static class Generators
{
    public static IReadOnlyList<IGenerator> All { get; } =
    [
        new MetaObjects.Codegen.Generators.EntityGenerator(),
        new MetaObjects.Codegen.Generators.DbContextGenerator(),
        new MetaObjects.Codegen.Generators.FilterAllowlistGenerator(),
        new MetaObjects.Codegen.Generators.RoutesGenerator(),
    ];
}
// codegen/Program.cs
using MetaObjects.Codegen;
return CodegenCli.Run(args, Generators.All, Generators.Configure);

Settings every generator shares. The GenConfig options that no flag and no .metaobjects/config.json key sets (ContextTypeName, PropertyNaming, ProvidedEnumNamespace, PackageNamespaces, TypeOverrides, Convention, UnmappedStrategy and the rest) are set in Generators.Configure, which dotnet meta init writes beside the list. It receives the config a run builds from its flags and the project config, and returns the one the generators see:

public static GenConfig Configure(GenConfig config) =>
    config with { ContextTypeName = "ShopDbContext", ProvidedEnumNamespace = "Shop.Domain" };

gen and verify --codegen both apply it, so verify regenerates what gen wrote. A codegen project from before 1.3.0 has no Configure: add the method, and pass it as the third argument in Program.cs. init never edits a file that exists.

Replace the empty list dotnet meta init wrote with the one above before the first gen: with an empty list gen writes nothing, and it needs an output directory (--out, or csharp.outDir in .metaobjects/config.json, below).

# Run the list: EF Core entities + AppDbContext + CRUD minimal-API routes
dotnet meta gen ./metaobjects --out ./Generated

# The drift gate: regenerate in memory and fail (exit 1, naming the files) if the
# committed ./Generated differs. Run it in CI.
dotnet meta verify ./metaobjects --codegen --out ./Generated

verify --codegen is the gate for generated code. dotnet meta verify ./metaobjects --templates ./prompts is a different gate, for prompt templates against their payloads (FR-004): it says nothing about generated code, and it fails with exit 2 when the directory it is given does not exist. A bare dotnet meta verify ./metaobjects runs that templates gate against prompts/ when it exists, else templates/, and fails the same way when neither exists. It also runs the codegen gate when --out <dir> and codegen/Generators.cs are present, and skips it with a note otherwise; name both subverbs to require both.

Every dotnet meta verify also prints the advisory authoring lints on stderr, whichever gates run: unflagged cross-file redeclarations (WARN_OVERLAY_IMPLICIT), whitespace in a node name (WARN_NAME_SURROUNDING_WHITESPACE, WARN_NAME_INTERNAL_WHITESPACE), references to a deprecated node (WARN_DEPRECATED_REFERENCE), then the field lint. None changes the exit code. The overlay lint reads the raw files, so it runs even when the model does not load; the name and deprecation lints read the loaded model and print nothing when it does not load (the load error is the gate's report). When the run includes the entity generator, dotnet meta verify also lists, once, each object-typed field that generator leaves off a projection or a write-through read model, with its fix. gen prints nothing for it. Mute each with --no-overlay-lint, --no-name-lint, --no-deprecation-lint or --no-field-lint, or the matching META_NO_*_LINT=1. The codes and message text match Node meta verify, gated by fixtures/model-lint-conformance/ and fixtures/field-lint-conformance/.

The output directory and the namespace are project settings, so gen and verify cannot disagree about them. Declare them once in .metaobjects/config.json; outDir is relative to the directory holding .metaobjects/:

{ "schema_version": 1, "csharp": { "outDir": "Generated", "namespace": "Acme.Blog" } }

Each generated type's namespace comes from the package bindings, keyed by that type's own metadata package: a type-level override (GenConfig.TypeOverrides), then a package-level one (PackageNamespaces), then the Convention rule (strip a package prefix, prepend a root, case each :: segment), then UnmappedStrategy. With none of those configured, the default convention applies: each :: segment PascalCased and joined with . (acme::billing is Acme.Billing), and the artifacts that belong to no single package (AppDbContext, routes) land in the namespace all the packages share. When they share no root, generation stops and asks for a namespace. Setting --namespace or csharp.namespace switches the default off and puts every type no binding places in that one flat namespace. The namespace must be a dotted path of C# identifiers. dotnet meta gen and verify read that flat namespace and, through csharp.packageNamespaces, the package bindings (below). The finer per-package bindings (TypeOverrides, Convention, UnmappedStrategy) are GenConfig properties, set in Generators.Configure (above).

Package-keyed output (opt-in). Two more csharp keys change where files land and which namespace a packaged type takes; a project that sets neither keeps the flat layout and the namespace rule above, byte for byte.

{ "schema_version": 1, "csharp": { "outDir": "Generated", "namespace": "Acme.Blog",
  "outputLayout": "package", "packageNamespaces": true } }
  • outputLayout: "flat" (the default) writes every file at the root of the output directory; "package" writes each per-object file under its metadata package, one directory per :: segment (acme::blog::Author is acme/blog/Author.g.cs). That covers the entity, value object, shared enum, names, filter allowlist, routes, reverse finders, callable, report export, the extract mirrors and the template tier. A root-level object, AppDbContext and the run-wide helpers stay at the root.
  • packageNamespaces: true puts each packaged type in its metadata package's namespace (PascalCased :: segments) even when csharp.namespace is set; that namespace then places only package-less objects and the run-wide artifacts. An object ({ "acme::blog": "Acme.Blog" }) maps packages to namespaces explicitly, the same as GenConfig.PackageNamespaces. Absent or false keeps the earlier rule, where a configured namespace turns the per-package derivation off. With true, every generated reference to a type in another namespace is written global::-qualified, so two same-named types never bind to each other.

dotnet meta init writes .metaobjects/config.json with both opt-ins for a new project, and never edits one that exists. gen and verify read the same keys, so the drift gate agrees with gen.

A type is never renamed to make room. Two nodes that would generate the same name in the same scope fail, naming both nodes and the remedy. A DbSet property in one context and a REST collection segment in one routes entry raise ERR_COLLECTION_NAME_COLLISION (the shared-ledger code, the same in every port); a type in one C# namespace, a file in one output path, a finder in one class and the other scopes raise ERR_NAME_COLLISION. The remedy is: map the packages to distinct namespaces, write them apart with outputLayout, or rename one (@collectionName for a DbSet and its route). The earlier package-qualified rename of a value object (AcmeAlphaNote) is gone; a value object keeps its name and sits in its package's namespace. An extract-tier private mapper may carry the package in a member name (FromAcmeAlphaNoteExtracted), because it is private to its class. Each package's shared enum is its own <package>/<Enum>.g.cs under the package layout, with its @intValueMap integers as member values and @description as its XML doc; the flat layout keeps the one Enums.g.cs. An entry narrowed with Include leaves a shared enum to another entity entry of the same run only when that entry accepts the enum's home object (its first consumer by resolution key), and declares the enum itself otherwise — so a single narrowed entry declares every enum its objects use and its output builds on its own, and an enum several narrowed entries use is still declared by exactly one of them.

With that, dotnet meta gen writes there, dotnet meta verify --codegen diffs against it, and a plain dotnet meta verify in CI runs the codegen gate with no flags. --out <dir> still works and wins over the config. A project that sets neither gets the skip note, which names the setting. The other ports ignore the csharp block.

dotnet meta gen --list is the catalog, and it shows what each generator requires. routes requires entity, db-context and filter-allowlist, because the handlers it emits reference their output; gen warns when one is missing from the list, since the result would not compile. --generators <names> narrows a run to the declared entries named; it never adds one, and naming an entry the list does not declare is refused.

Select objects. dotnet meta gen --entities Product,Supplier (comma-separated short object names, the name of the object without its package, as TypeScript's positional names and Python's --entities match) regenerates only those objects' files; dotnet meta verify --codegen --entities ... checks only the same files. Only per-object output narrows. A file built from the whole model, such as AppDbContext.g.cs, still renders from the whole model and is byte-identical to an unfiltered run, and a shared file (a shared enum, a helper) is the whole-model rendering too. A generator that reads the model root rather than the object list (api-docs, requirement-tests, template entries) is not narrowed. A narrowed run never deletes a stale file and never drops the manifest entry of a file it did not write, so the unselected objects' files are left as they are; run gen without the flag to sweep. Two refusals, both exit 2: --entities naming nothing (error: dotnet meta gen: --entities names no object.) and a name that matches no object (error: dotnet meta gen: --entities names 'X', which matches no object in the metadata.). An owned generator whose output is a single whole-model file declares public bool WholeModel => true;.

Own a generator. dotnet meta eject <name>... copies a reference generator into codegen/generators/. Every generator dotnet meta gen --list shows is ejectable except template, the Mustache primitive, which has no emit logic of its own to own. An ejected generator comes with the emitters it writes its output through (the enum, navigation, doc-comment and prompt-tier writers), so the copy owns the code that writes the file and not a shell around the package's; the naming and type-mapping tables (CSharpNaming, ValueObjectNames) stay in the package as the engine. Eject writes the three codegen/ files when they are missing, with the copy already listed as new Codegen.Generators.<Name>(); when codegen/Generators.cs exists it prints that entry for you to add in place of the packaged one. dotnet meta eject api-docs does the same for the api reference. Ejecting into a project whose codegen/Codegen.csproj pins an older MetaObjects.Codegen than the tool prints a warning naming the line to change. See Own your codegen → C#.

The metamodel reference. The metamodel-docs generator writes the metamodel vocabulary reference (metamodel/INDEX.md, providers.md, types/<family>.md) from the shared templates/metamodel/ Mustache set; a metamodel/<page>.mustache under its TemplateRoot overrides a shipped page.

The agent pages. The requirements generator writes requirements.toon, and agent-docs writes agent/requirements.md and the model-only agent/schema.md (tables, columns, keys, views, relationships and enums, named by this port's naming helpers). Both build their data from the docs view (MetaObjects.DocsView, its storage section for the schema) and render the shared templates/requirements/ and templates/agent/ Mustache pages, byte for byte what fixtures/docs-page-conformance/ pins (DocsPageConformanceTests). A <group>/<page>.mustache under TemplateRoot overrides a shipped page. agent-docs's SubDir is the directory the pages land in, agent by default ("llm" writes llm/schema.md; "" writes at the root), as in every port. agent/ui.md and the physical schema (SQL types, defaults, indexes) stay TypeScript's. The always-on agent file comes from dotnet meta agent-docs (no Node), which names these pages once a gen has written them.

Generators write through a code writer. MetaObjects.Codegen.Writer.CsWriter is where a generator's layout lives (ADR-0063): it owns the indent, the braces, the using lines and the blank lines, so a generator states what the file says and not how many spaces it takes. Every generator that emits C# source is written on it; the JSON, Markdown and template generators are not. Each such generator is a class whose file is built from one overridable method per piece (WriteFileHeader, WriteTypeDoc, WriteMembers and so on; in the routes generator WriteListRoute, WriteCreateRoute, WriteUpdateRoute and the rest, over a plan worked out once by PlanStandardRoutes or PlanTphRoutes), so an owned copy, or a subclass of the shipped one, changes the piece it wants and keeps the rest. Those methods are not a stability contract. A test keeps new hand-typed layout out of the generator source: a file that still builds text with AppendLine is on an allowlist with a written reason, and the list only gets shorter.

Give a copy back. dotnet meta eject --undo drops every owned copy that is identical to the shipped generator (the comparison ignores blank lines, order and trailing whitespace, and covers the emitters eject handed over with it); dotnet meta eject --undo <name>... drops only those. A named copy that differs is refused with exit 2 and nothing is removed, naming how far it differs, unless you pass --force to discard your edits. Every name is checked before anything is deleted. A companion file goes only when it is identical and no remaining owned generator uses it, and codegen/runtime/ goes only when every owned generator that used it is gone. --undo never edits codegen/Generators.cs or the project: it prints the line to change for each entry (new Codegen.Generators.X() back to new MetaObjects.Codegen.Generators.X()), and says plainly when nothing is identical. There is no doctor command: the one-line notice gen prints when identical copies exist (stderr, advisory, never the exit code) and dotnet meta gen --list, which marks each owned copy identical or DIFFERS, are where stale or identical copies show.

Strictness. dotnet meta gen loads leniently: an unknown @attribute is a warning naming the attribute, node and file, and gen generates anyway. dotnet meta gen --strict loads as verify does (ADR-0023): the same ERR_UNKNOWN_ATTR lines with a gen-specific hint (drop --strict), exit 1, before any file is written. verify itself stays strict unless you pass --lax.

Publishing a shared model (shared-model)

A C# project can publish part of its model for another repository to consume (FR-023). The shared-model generator writes <ModelName>.metaobjects.json and the manifest metaobjects.pkg.json that pins it by sha256, byte-identical to what the TypeScript generator writes (fixtures/shared-model-conformance/). Declare it in codegen/Generators.cs:

new SharedModelGenerator
{
    ModelName = "acme-common",
    Include = ["acme::common::**"],
    Files = ["metaobjects/meta.common.json"],
    OutDir = "shared",
}

ModelName, Include and Files are required; Exclude removes patterns from Include, and Version overrides the version recorded in the manifest, which otherwise is the project's <Version> (from the project file, else the nearest Directory.Build.props). It writes nothing and names the option to change when the selection is empty, is not closed over extends and reference attributes, or needs vocabulary outside the library's. Give OutDir a directory that holds nothing else. requirement.* nodes are published only when Requirements is set (requirements: true, default off); template.* nodes are never published. dotnet meta eject shared-model copies the generator into your project; the artifact bytes stay in the package, because a copy that changed them would publish a model a consumer's sync refuses. The consumer runs the Node meta deps sync, which stays the only writer of the lock and the snapshot.

Write your own generator

A generator is a class that implements IGenerator (MetaObjects.Codegen/Generator.cs): a kebab-case Name and Generate(GenContext), which returns the files (EmittedFile(path, content), the path relative to the output directory). ctx.Entities and ctx.Root are the loaded model. Optional members: OutDir (write somewhere other than --out), HandEdits.

// codegen/generators/EntityList.cs
using MetaObjects.Codegen;

public sealed class EntityListGenerator : IGenerator
{
    public string Name => "entity-list";

    public IEnumerable<EmittedFile> Generate(GenContext ctx)
    {
        var names = ctx.Entities.Select(e => e.Name).Order(StringComparer.Ordinal);
        yield return new EmittedFile("EntityList.g.cs",
            "// <auto-generated/>\npublic static class EntityList\n{\n" +
            "    public static readonly string[] Names = [" + string.Join(", ", names.Select(n => $"\"{n}\"")) + "];\n}\n");
    }
}

Wire it by adding one entry to the list in codegen/Generators.cs, beside the packaged ones:

    [
        new MetaObjects.Codegen.Generators.EntityGenerator(),
        new EntityListGenerator(),
    ]

dotnet meta gen then runs it with the rest of the list, and dotnet meta verify --codegen regenerates it and compares, so a hand edit to its output or a model change that moves it fails the gate like any packaged generator's. The example above is compiled and run by GeneratorAuthoringExampleTests. To start from a shipped generator rather than a blank class, dotnet meta eject <name> copies one in.

Documentation

dotnet meta init --with-docs writes the list with the api reference already in it (new MetaObjects.Codegen.Generators.ApiDocsGenerator { OutDir = "docs/csharp", ProjectName = "<dir>" }), so gen writes it. Init writes .metaobjects/config.json (the api, migrate and verify settings, described below) but no outDir: set "csharp": { "outDir": "<dir>" } there and a plain dotnet meta verify drift-checks the docs with the rest of the codegen output (verify --codegen compares the whole tree of each entry's OutDir, so keep it generated files only). Against an existing list, init prints the entry to add and edits nothing. Without the flag init is unchanged. The api pages carry a "Model / metadata" link only when the entry sets ModelBaseUrl: the C# port writes no model pages of its own, so a relative link would resolve to nothing and is omitted.

Schema migrations: the native path is EF Core Migrations, dotnet ef migrations add over the generated AppDbContext (ADR-0015 Amendment 1). The Node meta migrate is the reference migration helper, one option. The C# CLI is gen + verify only.

A declarative Mustache template-spec is one more entry in codegen/Generators.cs; see Declarative template-codegen below.

The codegen emits:

  • Author.g.cs — class per entity (a mutable attributed POCO, not a record).
  • <Report>.g.cs — keyless row class per view-backed report (object.report with a read-only @kind: view source); mapped in AppDbContext with DbSet + HasNoKey().ToView(...). It is served like a keyless projection: <Report>Routes.g.cs (MapGet list, MapPost answering 405, no {id} route) and <Report>FilterAllowlist.g.cs, with every derived field that has filter operators filterable and sortable (on a report an enum dimension sorts too; an entity's enum field does not). A derived field that can be null is a nullable member (long?, decimal?); a measure with @default, and in a @spine report a key or @required column of the spine entity, is not (long, decimal). No names artifact. An enum dimension reaches the wire as its string symbol only when the host serializes enums as strings (ConfigureHttpJsonOptions with a JsonStringEnumConverter): the routes return the row object and the host owns serialization. See reporting.
  • AppDbContext.g.cs — DbSet<Author>, projection .ToView(), @storage owned types via OwnsOne (single) / OwnsMany(...).ToJson(...) (@isArray array-of-VO), enum-as-string via HasConversion<string>(). An int-backed enum (@intValueMap) gets a converter pair that stores the declared integer and throws on a stored integer the map does not describe, and on a write of a value it does not describe (a cast integer, say), rather than storing another member's integer. On an isArray enum that pair is the element converter of an EF Core primitive collection; see Int-backed enum arrays.
  • AuthorRoutes.g.cs — CRUD minimal-API endpoints.
  • AuthorFilterAllowlist.g.cs — the server-side filter/sort allowlist feeding the generated list handler.

Entity and DbContext generator options

Renaming a property. A field's C# property is its PascalCased name. To spell some differently (an acronym, say), set one resolver on the config in Generators.Configure, GenConfig.PropertyNaming (Func<MetaField, string>, returning the name). The entity classes, the composite [PrimaryKey(nameof(...))], every AppDbContext model line and the reverse finders all read it, so the declaration and every reference agree. The hooks EntityGenerator.PropertyName and DbContextGenerator.PropertyName default to it; a subclass that overrides one must override the other the same way. The routes generator, the filter map and the credential stripping read the same resolver, and a hook that disagrees with it is refused.

Class attributes. EntityGenerator.EmitClassAttributes(w, entity, className, kind, ctx) (w is the CsWriter) is called for every class it emits (mapped entity, TPH subtype, abstract shape, value object), after the framework's own attributes and right before the declaration line. Override it to add an attribute without re-implementing EmitClassHeader.

The writer owns layout (ADR-0063). EntityGenerator writes every file on a MetaObjects.Codegen.Writer.CsWriter, and its hooks (EmitClassHeader, EmitClassAttributes, EmitClassDeclarationLine, EmitPropertyAttributes, EmitFileUsings, EmitClassBodyTrailer) take that writer instead of a StringBuilder. A hook writes complete lines with w.Line(...) or a using with w.Using(...) and never types an indent or a line break: the writer indents the line to where it is written. ValueObjectMemberAttributes returns lines with no indent for the same reason. A class that carries cross-field validators gets IValidatableObject added to its declaration line by the base class, even when an override of EmitClassHeader or EmitClassDeclarationLine wrote the line. The base class adds it to the last line written, so an override must write the declaration as its last line. The hooks are not a stability contract; an owned copy ejected with dotnet meta eject is yours to change.

DbContextGenerator writes on the same writer. Its three file-shape hooks (EmitUsings, EmitDbSetDeclarations, EmitOnModelCreatingBody) take the CsWriter in place of the StringBuilder; EmitUsings leaves the class body open with w.Open("{") and the generator writes the closing }. The hooks that return text (ContextUsings, ContextMemberLines, ContextPreambleLines, ContextTrailerLines, DbSetLine, EntityConfigTrailer, FieldTypeConfig, OwnedTypeConfig and the rest) return lines with no indent: each model entry is one statement, and the writer indents it where it is written. An entry that already carries an indent still reads right, because the writer removes an entry's common margin before it indents. A ContextUsings line is a using ...; directive, which the writer prints once, in the order given.

Each of those statement hooks also has an overload that takes the CsWriter as its first argument (OwnedTypeConfig(CsWriter w, ...), EntityConfigTrailer(CsWriter w, ...) and the rest, all but ContextUsings). Override that one to write a nested block with w.Braced(...), such as an OwnsOne(x => x.Nav, b => { ... }) or an if around several statements, instead of returning one string with embedded newlines. Its default writes what the text hook returns, so an existing text override still works. What one writer overload writes is a single model entry: ModelConfigChunkSize never splits it across two ConfigureModelNN methods.

Framework names. With csharp.packageNamespaces on, a package segment can shadow a framework namespace (acme::app::system derives Acme.App.System). Each generator therefore writes a framework reference through its Fx prefix ($"{Fx}System.Text.Json.JsonSerializer"), or through CSharpNaming.Framework(config, name), which gives global::System... exactly when package namespaces are on. Nothing rewrites generated text afterwards. If an emitted file still writes a bare reference that a namespace of the run shadows, the runner names that file in a warning.

One line at a time. Each of these is a protected virtual hook whose default is the line it replaces; override it, call base, and adjust. On EntityGenerator: ValueObjectMemberAttributes (the [JsonPropertyName] before each value-object member), ColumnAttributeArguments (the arguments of a mapped property's [Column(...)]; none leaves the attribute out) and TphDerivedTypeAttributes (the [JsonDerivedType] lines on a TPH base). On DbContextGenerator, the head of the file: ContextUsings (the using lines), ContextNamespace, ContextClassName (default AppDbContext; GenConfig.ContextTypeName does not change it), ContextBaseClass, ContextIsPartial, EmitContextConstructor and ContextMemberLines (members after the constructor, such as a partial void declaration a ContextTrailerLines call implements). The file is AppDbContext.g.cs whatever the class is called, and the routes generator still names AppDbContext: rename the class and you keep the routes consistent yourself. NamesGenerator.Render emits one <Entity>Names.g.cs; a null from it emits none.

Reverse finders. <Entity>Queries.g.cs takes the context as its first parameter, typed GenConfig.ContextTypeName (default AppDbContext). new EntityGenerator { EmitsReverseFinders = false } emits none, for a project that writes its own.

Scoping value objects. Include scopes the entities and value objects an entry emits, but a value object an emitted entity points at is still emitted, so the output compiles. Set ScopesValueObjectClosure = true beside Include to drop those too, when you provide the type yourself.

What the context configures beyond the column types. A single-column identity.primary @generation: assigned key is ValueGeneratedNever(), so EF always sends the caller's value, 0 included. An identity.reference relationship carries .HasConstraintName(...) from @constraintName, and .HasPrincipalKey(...) when @references names target fields other than the primary key. Under EmitAbstractShapes a concrete entity extends its abstract shape class, which carries no EF attributes, so the key, column names and @maxLength of the fields it inherits from there are configured in the context instead. A @storage: flattened value object pins each member to its flattened column; a value object nested inside it is one jsonb column holding the whole document (EF Core 8 cannot own a JSON column inside a table-split owned type). A field's @default is HasDefaultValue(v).HasSentinel(v) when it is a C# literal of the property's type (bool, string, number, enum member): EF then leaves the column out of an INSERT only when the value is the default anyway, so an explicit false, 0 or NULL is stored as set. A SQL expression (now(), anything function-like; a bare now is now()) or a timestamp, date or uuid literal is HasDefaultValueSql(...), and only on a @required property, because EF cannot tell a deliberate NULL from "not supplied". A scalar or enum property starts at its literal @default (its C# initializer), so a new entity the app never touches holds the sentinel and the column default applies. A timestamp or uuid property has no C# initializer from its @default, so a new entity carries the CLR default and EF sends it.

identity.primary @sequenceStart on a single-field increment key is the identity's START on Npgsql (a fresh database begins there). No start-only change ever restarts the sequence: Npgsql alone writes a start added as RESTART WITH n, a changed one as RESTART WITH m, and a removed one as RESTART WITH 1, each handing out ids live rows may hold. A Postgres context gets <Context>DesignTimeServices.g.cs, an IDesignTimeServices that wraps the model differ, so dotnet ef migrations add scaffolds every start-only change as SQL, Up and Down: ALTER TABLE … ALTER COLUMN … SET START WITH n (a removed start goes back to the identity default) and, for a declared start, a move of the counter FORWARD to GREATEST(n, max(id) + 1) when it sits below that, never back. A database rebuilt by replaying migrations begins at n as a fresh one does, and no migration hands out an id a live row holds. The same services scaffold a JSON column's comment.

It is design time only: nothing is registered at runtime, and Migrate() runs what the migration already holds. EF finds the services through [assembly: DesignTimeServicesReference(...)], which is generated beside the class when the context's assembly name is known (the single .csproj in the output directory or above it, or GenConfig.ContextAssemblyName). That covers EF's default layout, where the migrations live in the context's project. When the migrations or startup project is another one and dotnet meta gen can see it (the <Context>ModelSnapshot.cs is there) without the line, a project that declares an @sequenceStart fails with ERR_DESIGN_TIME_REFERENCE_MISSING, which names the project and the one line to add: without it a changed start scaffolds as RESTART. A run that cannot tell (no snapshot on disk yet), and a project that declares no start, get the warning with the same line instead. dotnet ef migrations add --verbose prints "Using design-time services from assembly …" when they are found.

The start in the model, and the services, are emitted only for a project whose .metaobjects/config.json names "migrate": { "dialect": "postgres" } (a self-hosted runner sets GenConfig.Dialect). Any other project gets neither, with a warning, and never needs the Npgsql package. UseIdentityStartMigrations(), the registration of an earlier runtime SQL rewrite in the 1.2.4 release candidates, is no longer generated, so a call to it does not compile; remove the call.

CHECK constraints are the ones meta migrate creates: each scalar field.enum and each validator that can carry one (numeric, length, regex, comparison, requiredWhen, presentIff, atLeastOne, exactlyOne, with @condition) is a modelBuilder.Entity<T>().ToTable(t => t.HasCheckConstraint(name, sql)) line, with migrate's name (<table>_<column>_numeric_chk, … or the validator's @constraintName) and its expression text, so a table built by an EF migration and one built by meta migrate carry the same constraints. They are declared for migrate.dialect postgres, sqlite or d1 only, because the text is dialect-specific (~, IS DISTINCT FROM, num_nonnulls on Postgres); migrate.checks.skipRedundant (GenConfig.SkipRedundantChecks) leaves out the ones the column already enforces, as migrate does. The shared corpus fixtures/check-constraint-conformance/ pins the names and text in both ports.

Decimals and null members on the wire

What the generated API writes is the project setting wire in .metaobjects/config.json (api-contract.md, "The wire setting"). With no setting, it writes what System.Text.Json writes: a decimal is a JSON number that keeps its scale (12.50, 0.0000001), and a value object's null member is null with its key present. That is the 1.0.x output. "wire": { "decimals": "string" } writes the canonical string of ADR-0019 Amendment 1 (12.50 is "12.5", zero is "0"). "nullMembers": "omit" leaves a null member out ([JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] on each nullable member), and "emit" is what the default already writes.

Input is the same in every mode. It may be a string or a number, is read exactly, and is 400 validation when it has more fraction digits than @scale or more integer digits than @precision - @scale (no @scale beside @precision means 0). A filter operand compares exactly; a bad one is 400 invalid_filter_value. On SQLite a decimal is read at 15 significant digits. Every port runs the shared vectors in fixtures/decimal-wire/.

dotnet meta gen writes DecimalWire.g.cs once per namespace that has a decimal (named DecimalWire.<Namespace>.g.cs when the model binds more than one namespace; MetaNetValidation follows the same rule). By default a decimal property carries [DecimalWire.Number], or [DecimalWire.Number(precision, scale)] with @precision. Under "decimals": "string" it carries the string converter, or [DecimalWire.Declared(precision, scale)]. A decimal array is an IList<decimal>. A stored value the CLR decimal cannot hold answers 500 {"error": "decimal_out_of_range"} (DecimalRangeEndpointFilter). An owned routes generator copies DecimalWire.cs and DecimalRangeEndpointFilter.cs. Do not strip the attributes or delete DecimalWire.g.cs to change the output: they also check input. Set wire and regenerate.

A field.duration is a TimeSpan carrying [DurationWire.Iso], which reads and writes the ISO-8601 form every port shares (PT1H30M, and on input P1W, P2DT3H) instead of System.Text.Json's 01:30:00. It writes up to seven fractional digits, a TimeSpan tick, and truncates a longer input fraction toward zero. On Npgsql it is an interval column. EF reads an interval through Npgsql's own TimeSpan conversion, which (as of Npgsql 8.0.5) silently drops a negative month or year part ('-1 mons' reads as PT0S) and wraps a day count past TimeSpan's range, so the generated context maps each duration column through NpgsqlInterval instead (DurationIntervalMapping, DurationIntervalArrayMapping, emitted beside AppDbContext) and refuses either one on read. LINQ still translates as it does on Npgsql's own mapping: TimeSpan members (TotalSeconds, Hours, ...), a timestamp plus a duration, comparison, ordering, Min, Max, EF.Functions.Sum, and Contains / Count / Any on a duration array. A compiled model (dotnet ef dbcontext optimize) keeps the mapping and the refusal; EF Core 8's compiled model carries no element type, so there a duration array reads and writes but is not queryable as a collection. On any other provider a value converter stores the 64-bit microsecond count, so sorting and range filters follow the span. Both columns hold microseconds, so a tick below one is dropped on write. TimeSpan's own range is the only limit: a longer span is refused, never wrapped. DurationWire.g.cs is emitted once per namespace that has a duration, and an owned routes generator also copies DurationWire.cs.

<Entity>Names — the physical names, as constants

names is opt-in — list new MetaObjects.Codegen.Generators.NamesGenerator() in codegen/Generators.cs (dotnet meta gen --list names the whole catalog). Listing a generator is not owning it: to change what names emits, dotnet meta eject names copies its source into codegen/generators/ (see "Own a generator" above). When listed, a project gets <Entity>Names.g.cs. It carries the physical database names for one object as const strings:

// SubscriberNames.g.cs (using/namespace elided)
public abstract class SubscriberNames
{
    public const string Type = "object";
    public const string SubType = "entity";
    public const string Name = "Subscriber";

    public const string SourcePrimaryType = "source";
    public const string SourcePrimarySubType = "rdb";
    public const string SourcePrimaryKind = "table";
    public const string SourcePrimaryTable = "subscribers";

    public const string CreatedAtField = "createdAt";
    public const string CreatedAtColumn = "created_at";
    public const string IdField = "id";
    public const string IdColumn = "id";

    public const string IdentityPrimaryType = "identity";
    public const string IdentityPrimarySubType = "primary";
    public const string IdentityPrimaryName = "primary";

    public static readonly Dictionary<string, string> ColumnsByField = new(System.StringComparer.Ordinal)
    {
        ["createdAt"] = CreatedAtColumn,
        ["id"] = IdColumn,
    };
}

The artifact mirrors the metadata tree. Every node it describes — the object, each source.rdb, each identity, each index — carries its own Type, SubType and Name, and a physical name sits under the member that says what it IS: SourcePrimaryTable, SourceReplicaView, SourcePrimaryProc, using the metamodel's own FR-016/ADR-0018 kind→alias map. SubscriberNames.SourcePrimaryView does not exist, so the read site answers "table or view?" instead of the reader having to. Sources are keyed by @role, which is what gives a write-through entity's replica view a member of its own (SourceReplicaView) — it declares two physical names and the artifact used to carry one.

Name changed meaning in 0.25.0 and still compiles. It held the PHYSICAL name; it now holds the object's own name. [Table(SubscriberNames.Name)] in hand-written code binds a table called Subscriber instead of subscribers — silently. Kind, ReadOnly and a top-level Schema are gone and fail to compile, which is the loud half. Grep for Names.Name before regenerating. ReadOnly is not relocated but REMOVED: it was never metadata, only a derivation over @kind — ask SourcePrimaryKind instead.

An identity or index carries an Index member — the declared index name; on Postgres meta migrate creates a name over 63 bytes as its first 63 bytes, and the EF context declares that cut name (stored names) — only where one exists: identity.secondary and index.lookup. An identity.primary gets none, because no port's codegen names a primary key (Postgres migrations hardcode <table>_pkey, SQLite emits an unnamed PK), and carrying that would restate a migrate-only formula in the artifact built to stop exactly that.

A @storage: flattened value-object field gets one constant per member column (ShipToStreetColumn, keyed shipTo.street in ColumnsByField). Its own ShipToColumn is still emitted but [Obsolete]: the table has no column by that name. Declaring it raises no warning; reading it does, so a project that never reads it builds clean under TreatWarningsAsErrors.

const, not static readonly: a [Table("...")]/[Column("...")] attribute argument must be a compile-time constant, and those two attributes are the whole reason this artifact can replace a literal there rather than sit beside one. The generated entity class and AppDbContext already reference these constants — [Table(SubscriberNames.SourcePrimaryTable)], [Column(SubscriberNames.CreatedAtColumn)] — instead of embedding the same physical names a second time, so the constant and the EF mapping cannot drift apart.

Prefer a typed handle where one exists. If the ORM gives you a type-checked object for the same thing, use that. Replacing it with a string constant trades an error the compiler catches for one the database raises at runtime. These constants are for the places with no typed handle: raw SQL, a migration script, a log line, an external system's column mapping.

Here, that handle is the generated EF Core property. If you are writing a LINQ query, use it (db.Subscribers.Where(s => s.CreatedAt > cutoff)) — it is type-checked against the DbContext model, and swapping it for SubscriberNames.CreatedAtColumn trades a compile error for a runtime one. Reach for the constant instead in raw SQL (FromSqlRaw/FromSqlInterpolated), a migration script, a log line, or an external system's column mapping.

It follows extends, so a constant you do not find on a class is on its base. <Entity>Names is a public abstract class — abstract rather than static precisely so it can be inherited — and an object that extends another produces a class that extends the other's:

public abstract class CouponAuthNames : AuthNames
{
    public const string CouponAmountField = "couponAmount";
    public const string CouponAmountColumn = "coupon_cents";
    public new const string Type = "object";
    public new const string SubType = "entity";
    public new const string Name = "CouponAuth";
    // SourcePrimaryTable / IdColumn / … are the base's. A C# const is inherited, so
    // CouponAuthNames.SourcePrimaryTable and CouponAuthNames.IdColumn both resolve.
}

new on Type/SubType/Name because every artifact declares its own three and a derived const hides the base's rather than clashing with it.

Two forms, and which one you get is structural. An object with its OWN source declares its own Source<Role>* members; one that INHERITS its source — a TPH subtype sharing its base's single table — declares none and takes them from the base. An abstract base a persisted entity extends gets a class of its own carrying the columns it declares and no source members at all — it has no table and must never acquire one. ColumnsByField stays complete on every class, inherited entries included.

Column names come from the project's naming setting in .metaobjects/config.json (ADR-0058), the one every port reads, default snake_case (what meta migrate creates). A database whose columns are named exactly like the fields declares "naming": { "columns": "literal" }; through 1.0 that was this port's default. One whose columns are the field names with the first letter upper-cased (requestURL → RequestURL) declares "pascal". A host that needs its own rule (an acronym list, a prefix) registers it with NamingStrategies.RegisterColumns(name, n => ...) before it reads the config, and names it there; the stock dotnet meta tool knows only the built-ins. dotnet meta gen and dotnet meta verify --codegen both read the setting, so a plain run and the drift gate resolve the identical column strings; --column-naming is refused (physical-naming.md). verify --codegen says so when the committed output was generated with another rule, rather than telling you to regenerate. See the "Column naming" section of features/field-types.md.

rules-names — the business-rules names, as constants

The rules-names generator (RulesNamesGenerator) is ADR-0067's layer 0 for the business-rules vocabulary (business rules). It writes nothing for a model that declares no lifecycle and no operation. For one that does, it writes:

  • <Entity>Rules.g.cs for each entity with a lifecycle. Each lifecycle field becomes a nested class holding Field, Initial (the enum's @default), TerminalStates (the members no transition leaves), States, Transitions and Permissions. Permissions maps each transition that derives a command to the permission that command asks the policy about: its @permission, or the derived <package>.<Entity>.<transition>. A @public transition, and one a declared command claims, has none. rules.lifecycle.commands decides which transitions derive a command, and verify's rules gate uses the same derivation.
  • <Api>Operations.g.cs for each api.operational, with a nested class per operation holding Name, Permission (absent when @public) and Errors (its @errors codes).
  • RuleErrorCodes.g.cs, once per run, with the codes the enforcing shell answers on its own (not_found, forbidden, invalid_transition, transition_condition_failed, state_managed).
if (!policy.Allows(user, PurchaseRequestRules.Status.Permissions.Submit)) return Results.Forbid();
if (request.Status != PurchaseRequestRules.Status.States.Draft) return Conflict(RuleErrorCodes.InvalidTransition);

Every name is a const string, so it can stand in an attribute argument or a switch label, and hand code that uses one stops compiling when the model renames it. Two names that fold to one C# member (in_review and inReview) are refused, naming both. Include on the entry scopes it as it does any generator: an entity's file follows the entity, and an API's file follows its package. This is a layer generator, separate from the flat ones (ADR-0067 §5), so adding it changes no other generator's output.

contract-types — the create and update records

The contract-types generator (ContractTypesGenerator) is ADR-0067's layer 1 for writes. For each writable entity (a concrete object.entity with a writable primary source) it writes <Entity>Contracts.g.cs, next to the entity, with two sealed records:

  • <Entity>Create: what a client sends to create a row. It leaves off what the server owns (a derived field, an @autoSet stamp, a readOnly field, the TPH discriminator) and a key the server generates (@generation: increment or uuid). A key the client chooses stays. A member that is required and has no @default is a C# required member, so System.Text.Json refuses a body that omits it.
  • <Entity>Update: what a client may change. It leaves off the same server-owned members, every key field (the route names the row) and a writeOnce field (frozen after create; it stays on <Entity>Create). Every member is optional. Bind it with <Entity>Update.From(body, options), which records the keys the body carried: Has("note") is true for {"note": null} and false for {}, so a PATCH can leave an omitted member alone and clear an explicit null. A body that is not a JSON object throws JsonException. Validate refuses null on a required member. A field whose C# name is one of the record's own members (Fields, Present, Has, From, Validate) is refused at generation, naming the entity and the field; rename the field.

Both records carry the entity's validation attributes ([MaxLength], [StringLength], [Range], [RegularExpression], [EmailAddress], the array counts) and its wire converters (decimal, duration, strict uri/inet), written by ContractMembers, the one copy EntityGenerator writes its own from. A required string keeps its non-empty floor in both: on update it applies when the member is sent. Enum, value-object and map members name the entity's own types, so entity runs in the same project (Requires: entity). Bind with the application's JSON options; an enum member needs the JsonStringEnumConverter the application registers (see Use).

The lifecycle field stays on both records. The service shell checks a create against the initial state and refuses a change on the generic update with 409 state_managed (ADR-0066 §6), so it has to see the member. This is a layer generator, separate from the flat ones (ADR-0067 §5), so adding it changes no other generator's output. Eject hands ContractMembers over with either generator.

Report export

A served report (a view-backed object.report) can be downloaded as a file: GET /api/<segment>?format=csv|json|xml, the contract in api-contract.md. It is on when you list the report-export generator beside routes in codegen/Generators.cs, and not otherwise: with it unlisted, the generated routes are byte-identical to before.

new ReportExportGenerator { MaxRows = 50_000, XmlNulls = ReportExportXmlNulls.Nil, CsvBom = false }
  • Wiring is the generator list. routes asks the run (GenContext.ReportExportMaxRows) whether a report-export entry is listed, so an ejected copy (dotnet meta eject report-export) wires the routes exactly as the packaged one does. dotnet meta gen --generators routes alone leaves it off.
  • Writes one shared ReportExportWriter.g.cs per project (CSV quoting, CRLF, the injection guard, the ExportCsvBom constant, XmlWriter output, wire-form conversion of a cell) and one <Report>Export.g.cs per served report (its columns in derived-field order). The generated code uses TextWriter, XmlWriter and System.Text.Json only and adds no package. The HTTP side (?format=, the three 400 envelopes, Content-Disposition) is ReportExportHttp, one of the helper-runtime files dotnet meta eject routes copies.
  • MaxRows (default 100,000) is the export cap. With ?format set it governs and report_too_large never answers; without it the list route's ReportMaxRows (10,000) is untouched.
  • XmlNulls defaults to Nil: a null field is an empty element with xsi:nil="true" and the root declares xmlns:xsi. That is what XmlSerializer writes for a nullable value type and what DataContractSerializer writes for any null, and it keeps a null apart from an empty string. Empty writes a bare empty element and declares nothing.
  • JSON is the list route's body (the array, or { rows, total } with withCount) through the host's configured JSON options (so a wire setting and a JsonStringEnumConverter apply as on the list route), served as application/json.
  • A character XML 1.0 cannot carry is written as U+FFFD rather than failing the export.

Use

// Program.cs
using System.Text.Json.Serialization;
using Acme.Blog;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(opts => opts.UseSqlite("Data Source=blog.db"));
// Enum fields (role) travel as their symbols ("writer"), not integers: the routes return the
// entity and the host owns serialization, so without this POST {"role":"writer"} is a 400.
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));

var app = builder.Build();
using (var scope = app.Services.CreateScope())
    scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();  // the sample creates its own table

app.MapAuthorRoutes();   // generated — GET/POST/PATCH/PUT/DELETE on /api/authors
app.Run();
dotnet run --urls http://127.0.0.1:5077
curl -X POST -H 'content-type: application/json' -d '{"name":"Ada","role":"writer"}' http://127.0.0.1:5077/api/authors   # 201
curl -g 'http://127.0.0.1:5077/api/authors?filter[role][eq]=writer'                                                      # 200, the row

A filter works on a field marked @filterable (name and role above); any other field answers 400 invalid_filter_field.

Postgres. Swap UseSqlite(...) for UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")) and add Npgsql.EntityFrameworkCore.PostgreSQL instead of the SQLite package. EnsureCreated is for samples; on Postgres create the tables with the Node CLI's migrations (meta migrate, ADR-0015) — the C# port has no migrate surface.

EF Core does the rest — the generated entities and AppDbContext are plain EF Core with no MetaObjects types in them. Note the one exception: generated routes emit using MetaObjects.AspNetCore; for the shared filter/sort helpers, so a project that generates routes with the packaged generator references the MetaObjects.AspNetCore package (<PackageReference Include="MetaObjects.AspNetCore" Version="1.3.0" />). Entities-and-DbContext-only projects do not. MetaObjects.Codegen and the dotnet meta tool carry no EF Core or ASP.NET Core dependency; before 1.3.0 the helpers lived in MetaObjects.Codegen under MetaObjects.Codegen.Runtime, and dotnet meta gen / verify warn when generated routes import MetaObjects.AspNetCore and the project compiling them does not reference it.

Owning the routes, helpers included. dotnet meta eject routes copies the routes generator into codegen/generators/ AND the helper source its output calls into codegen/runtime/: FilterParser, FilterParseResult, FilterPredicate, EfCoreFilterDispatch, ValueObjectValidator, ConstraintErrors and Iso8601TimestampConverter, each under the namespace Codegen.Runtime. The owned generator's output imports Codegen.Runtime instead of the package. Compile the folder into your app (<Compile Include="../codegen/runtime/**/*.cs" />) and the generated routes need no MetaObjects.AspNetCore reference; a fix to the filter parser is then an edit in your repo, not a wait for a release. What stays in MetaObjects.Codegen is core: ExtractObject (the reply parser the prompt tier calls) and M2MResolver (metadata-driven M:N traversal), plus the loader, registry, render and verify. dotnet meta gen --list reports the copy identical or per-file DIFFERS, verify --codegen does not treat it as drift, and Own your codegen → C# has the diff recipe for pulling an upstream fix into it.

Consumer dependencies. The generated AppDbContext and the Program.cs wiring above use EF Core (AddDbContext, DbContext, UseSqlite), which MetaObjects does not pull in for you — add the EF Core provider package for your database to the consuming app (Microsoft.EntityFrameworkCore.Sqlite above, Npgsql.EntityFrameworkCore.PostgreSQL for Postgres).

// Optional handwritten service over the generated DbContext
public class AuthorService(AppDbContext db)
{
    public Task<List<Author>> ListAsync() => db.Authors.ToListAsync();

    public async Task<long> CreateAsync(string name, string? bio = null)
    {
        var author = new Author { Name = name, Bio = bio };
        db.Authors.Add(author);
        await db.SaveChangesAsync();
        return author.Id;
    }
}

FR-004 — render

using MetaObjects.Render;

var provider = new FilesystemProvider("./prompts");
// The @payloadRef value object's own POCO, emitted by EntityGenerator (ADR-0056).
var payload = new WelcomePayload
{
    DisplayName = "Ada",
    PostCount = 12,
    Posts = new List<PostSummary> { new() { Title = "Hello" } },
};

string output = Renderer.Render(new RenderRequest {
    Ref = "lobby/welcome",
    Payload = payload,
    Provider = provider,
    Format = "xml",
});

Verify in MetaObjects.Render drift-checks every template.* against its @payloadRef. Wire it into your CI step or invoke dotnet meta verify directly. The renderer reads a POCO through its [JsonPropertyName] wire names, so {{postCount}} resolves against the PostCount property and {{#hasPosts}} works.

FR-006 — response parsing

OutputParserGenerator (in MetaObjects.Codegen) emits one <PromptName>.response.cs file per responding template.prompt — one declaring @responseRef. The static <PromptName>Parser class follows the BCL Parse/TryParse dual-API convention — Parse throws on bad input, TryParse returns a bool plus an out-error string.

ADR-0052: the shape parsed INTO is @responseRef, never @payloadRef (which types the request the prompt renders outbound), and template.output gets no parser at all. The parser returns the @responseRef value object's own POCO (<Vo>.g.cs, from EntityGenerator; ADR-0056) — so wire entity in the same run. A @required member is enforced by a generated JsonTypeInfo modifier rather than the C# required keyword, because the REST tier shares the POCO. The strict tier is JSON-only: an @responseFormat: xml reply gets the tolerant extract and nothing strict.

// generated/NpcResponse.response.cs
public static class NpcResponseParser
{
    private static readonly JsonSerializerOptions Options = new()
    {
        PropertyNameCaseInsensitive = false,
    };

    /// <exception cref="JsonException">malformed JSON or schema mismatch.</exception>
    public static NpcResponse Parse(string text) =>
        JsonSerializer.Deserialize<NpcResponse>(text, Options)
            ?? throw new JsonException("deserialized to null");

    public static bool TryParse(string text,
        [NotNullWhen(true)] out NpcResponse? value,
        [NotNullWhen(false)] out string? error) { ... }
}

The [NotNullWhen] attributes mean nullable-flow analysis lets you use npc without a null-check after a true return, and error without one after false.

Consumer wiring:

string llmResponse = await myLlmClient.CompleteAsync(promptText);

// Throwing path
var npc = NpcResponseParser.Parse(llmResponse);

// TryParse for explicit error handling
if (NpcResponseParser.TryParse(llmResponse, out var npc, out var error))
    return Ok(npc);
else
    return BadRequest(new { error });

MetaObjects.Render's Verify walks both template subtypes, catching payload ↔ template drift at build time. Cross-port design is at ADR-0010; the feature reference is at features/templates-and-payloads.md.

Consumer dependency. System.Text.Json ships in the .NET 8 BCL — no NuGet package to add. The generated parser uses the strict (case-sensitive) default options.

Requirement tests

Declare what the software must do as requirement.* nodes and dotnet meta verify checks them on every run; the requirement-tests generator then writes one xUnit test per tested requirement. The generator is a reference helper and a recommended approach, not a contract: dotnet meta eject requirement-tests copies it to codegen/generators/RequirementTestsGenerator.cs for you to change. The checks in verify are core and are not ejectable.

# The gate: runs on every verify, beside whichever drift gate it was given
dotnet meta verify ./metaobjects --codegen --out ./Generated
dotnet meta verify ./metaobjects --codegen --out ./Generated --require-implementers
# Recommended once the ledger is clean: use this form in the project's verify script or pre-push hook

# The tests: the same run as everything else codegen/Generators.cs declares. The entry's
# OutDir puts them in the test project, which references xunit; the app's --out does not.
dotnet meta gen ./metaobjects --out ./Generated
dotnet meta verify ./metaobjects --codegen --out ./Generated

Give the entry an OutDir in codegen/Generators.cs (below): the tests need xunit, which the project compiling --out does not reference, so they go into the test project. gen writes them there and verify --codegen compares them there, in the same run that writes and checks your entities. Point OutDir at a directory that holds generated files only: verify --codegen compares the whole tree.

Per metamodel package the generator writes Requirements_<pkgKey>_Witnesses.g.cs, an interface with one default member per test that is not skipped, and Requirements_<pkgKey>_Tests.g.cs, one [Fact] per requirement ([Fact(Skip = "…")] for a planned or retired one). Both are in <namespace>.Requirements and are rewritten whole on every run. The tests construct one class of yours, <namespace>.RequirementWitnesses by default, which implements every generated interface. Until that class exists the test project does not compile. Implement each member explicitly:

using Acme.Shop.Requirements;
using Xunit;

namespace Acme.Shop;

public class RequirementWitnesses : Requirements_acme_shop_Witnesses
{
    void Requirements_acme_shop_Witnesses.req_acme_shop_Orders_Recorded__object_entity()
    {
        // fails when a placed order has no row
    }
}

A requirement that becomes live adds a member whose default fails the test (unimplemented requirement: <id> - write <WitnessClass>.<key>() so that it fails when: <counterexample>), with no compile break. One that is retired or deleted removes its member, and an explicit implementation of it then stops compiling (CS0539). A public void req_…() implements the member implicitly, and a stale one keeps compiling, so it goes stale silently. If a test reports unimplemented requirement for a witness you believe you wrote, the method is not implementing the member: in the implicit form it must be public, non-static, parameterless and named exactly as the interface names it.

The seven options are init properties on the generator, set on its entry in codegen/Generators.cs:

// codegen/Generators.cs
using MetaObjects.Codegen;
using MetaObjects.Core.Requirement;   // RequirementTestGrain, IRequirementTestFilter

public static class Generators
{
    public static IReadOnlyList<IGenerator> All { get; } =
    [
        new MetaObjects.Codegen.Generators.RequirementTestsGenerator
        {
            OutDir = "tests/Acme.Shop.Tests/Generated",
            WitnessClass = "Acme.Shop.Tests.Witnesses",
            Grain = RequirementTestGrain.Member,
            WarnUncovered = false,
        },
    ];
}

After dotnet meta eject requirement-tests the entry names your owned copy instead, new Codegen.Generators.RequirementTestsGenerator { … }. Write each entry fully qualified, as above: an owned copy and the packaged class share a simple name, so adding using MetaObjects.Codegen.Generators; beside using Codegen.Generators; makes each new <Name>Generator() ambiguous (CS0104).

Property Meaning
OutDir Where the tests are written, relative to the directory the run starts in. Default: the run's --out. Set it to the test project's directory.
TestNamespace Namespace of the generated tests. Default <namespace>.Requirements.
WitnessClass Full name of your witness class. Default <namespace>.RequirementWitnesses.
Grain RequirementTestGrain.Concern (default): one test per distinct <type>.<subType> a requirement claims. Member: one per distinct implementedBy reference that resolves.
Filter An IRequirementTestFilter (bool Include(RequirementView view)) that replaces the default of functional requirements at L4 and L5. The view carries SubType, Level (int?, null when not declared), Status, Path, Package and ImplementedByTypes.
Renderer An IRequirementTestRenderer (in MetaObjects.Codegen); it returns a RenderedTest to replace the text of one test, or null to keep the default.
WarnUncovered true (default): one warning naming up to five requirements the filter left out.

The hook types, the identity function and the digest stay in the package when you eject; the owned copy uses them from there. A package that loses its last requirement loses its two files: dotnet meta gen deletes them through the hash manifest (an edited one is refused by name), and until then dotnet meta verify --codegen reports each as committed but a fresh regen would not emit it. The model and the other ports' spelling are in Generated requirement tests and witnesses.

Declarative template-codegen (TemplateSpecGenerator)

Beyond the built-in EF Core / routes suite, dotnet meta gen runs declarative Mustache template generators from a JSON template-spec — the cross-port contract shared with the Python port (see docs/features/codegen-concepts.md and the neutral data dict in docs/features/codegen-data-shapes.md). The spec is declared where every generator is, as an entry in codegen/Generators.cs:

new MetaObjects.Codegen.TemplateCodegen.TemplateSpecGenerator
{
    Spec = "template-spec.json",   // from the directory gen runs in, as --out is
    TemplateRoot = "templates",    // optional; default the run's --template-root, else prompts/ when it exists, else templates/
},
// template-spec.json — the cross-port shape
{ "generators": [
    { "name": "entity-doc",
      "scope": "perEntity",            // perEntity | perPackage | perModel
      "outputPattern": "{package}/{Name}.md",
      "template": "entity-doc",          // resolved under TemplateRoot
      "format": "markdown" }            // optional; a registered escaper format
]}

dotnet meta verify --codegen regenerates the same entry, so the gate and the generator agree. Through 1.0 the CLI also read --template-spec or a project-root template-spec.json on its own; neither is read now, and a run that finds either with no TemplateSpecGenerator entry fails before writing anything, with a line that starts dotnet meta gen: found 1.0 template-spec configuration (. See the migration section.

Each spec entry derives the neutral template data dict for its scope (MetaObjects.Codegen.TemplateCodegen.TemplateData) and names each file via the outputPattern placeholders ({name}, {Name}, {package}). The entry's files land under --out, or under its own OutDir when it sets one, and are gated byte-identical against the shared fixtures/template-codegen-conformance/ corpus. A target field is rejected (C# has no output-target concept); a missing spec file, a bad template ref or a wrong TemplateRoot surfaces as a clean error, not a stack trace. The write path decides from the committed hash manifest, not the @generated header, so the template need not emit one (see codegen-concepts).

Angular 18 frontend

C# 12 / .NET 8 backends pair cleanly with an Angular 18 client built from the universal @metaobjectsdev/angular runtime + @metaobjectsdev/codegen-ts-angular codegen packages — which are source-only today, not published to npm (build them from the TS workspace; see the recipe). The generated ASP.NET Minimal API routes (from MetaObjects.Codegen RoutesGenerator) speak the same URL grammar and wire format the Angular client expects — no special-casing.

End-to-end recipe — CORS wiring, dev-server port conventions, base-URL configuration, the dotnet meta gen command sequence that emits both halves — lives at docs/recipes/csharp-angular18.md.

Today's RoutesGenerator honours pagination (?limit/?offset), sort (?sort=<field>:asc|desc against a static per-entity allowlist), and the ?withCount=1 envelope ({ rows, total }) that the Angular grid hook always sends. Filter operators (eq / ne / gt / gte / lt / lte / in / like / isNull) per api-contract.md ship too — the generated <Entity>FilterAllowlist (FilterAllowlistGenerator) feeds ListQueryParser.Parse + EfCoreFilterDispatch.Apply, both wired directly into the generated list handler; the REST-standard query (?search, filter[or] / filter[and], the named refusals) is read the same way. A read-only projection (source.rdb @kind: view) and a view-backed report get the same filter and sort on their list route, against an allowlist of their own fields.

The api block of .metaobjects/config.json reaches the generated routes through the loaded root (MetaRoot.Api): api.pagination pages every entity, TPH and projection list route, and api.unknownFields is checked by UnknownFieldCheck in the helper runtime, matching a key the way the route binds the body (the app's System.Text.Json options). What each setting answers is in api-contract (page size, unknown fields). dotnet meta init writes .metaobjects/config.json with the same new-project settings as meta init: api.pagination 50/1000, api.unknownFields: reject, verify.handEdits: fail and migrate.foreignKeyIndexes: true; an existing config is left alone. A project that sets no api.pagination still pages: a list with no limit answers the first 50 rows (ApiSettings.DefaultPageLimit, the default of every port) and an explicit limit is served as asked, with no maximum. A bound that is not a non-negative integer is 400 pagination.invalid_value with or without the setting.

Known gaps (full list with workarounds in KNOWN_GAPS.md): a single sort key only (G3); the sort set is wider than the contract's sortable set (G10); the <Entity>View / <Entity>Views names are reserved for a write-through entity's generated read model; an EmitMappedClass override does not reach that read model; M:N traversal on a write-through entity is not routed through the replica view; there is no metadata-driven runtime tier (EF Core output is generated code), and no migrate surface (EF Core Migrations, or the Node meta migrate reference helper).

Capability snapshot

Feature Status
Entities + fields Yes
Relationships + FK Yes (EF Core + Postgres FK clause)
Source kinds (table / view / storedProc) table + view fully shipped; storedProc / tableFunction / materializedView partial
field.currency / field.enum / field.object + @storage Yes (incl. EF Core OwnsOne for flattened; OwnsMany(...).ToJson(...) for @isArray array-of-VO jsonb)
Templates + render (FR-004) Yes (MetaObjects.Render; Mustache only — a Jinja body is refused with ERR_TEMPLATE_ENGINE_UNSUPPORTED, ADR-0061)
Output parser codegen (FR-006) Yes (OutputParserGenerator — Parse/TryParse BCL pattern)
Payload-VO codegen Yes — the payload IS the value object's own POCO from EntityGenerator (ADR-0056); no separate payload generator
Declarative template-codegen Yes — a TemplateSpecGenerator entry in codegen/Generators.cs (scope perEntity/perPackage/perModel + outputPattern; the cross-port JSON contract shared with Python)
Migrations EF Core Migrations is the native path; the Node meta migrate is the reference helper, one option (ADR-0015 Amendments 1 and 2) — no C# migrate surface
Drift verify dotnet meta verify (template drift, FR-004; --codegen regenerates the list in codegen/Generators.cs and diffs it)
API reference docs Yes — the ApiDocsGenerator entry in codegen/Generators.cs (OutDir, ApiSubDir, ProjectName, ModelBaseUrl); dotnet meta docs was removed in 1.1.0 (migration)
Model explorer Yes, with no Node — a DocsSiteGenerator entry in codegen/Generators.cs (registry name docs-site): under <OutDir>/<SubDir> (default site) it writes the explorer app (index.html and assets/, the same bytes in every port, embedded in MetaObjects.Codegen), explorer.json (the docs view, built from the loaded model by MetaObjects.DocsView; byte-identical to TypeScript's for the same inputs, gated by fixtures/explorer-conformance/), explorer-model.js and explorer-stamp.js. Each object lists the files generated for it, recorded under each generator's registry name: this run's, laid over what the committed hash manifest records outside the directories the run's orphan sweep clears, so it never lists a file the run deletes. The runner runs it after every other entry, so gen and verify --codegen list the same files. Options: SubDir, Title (default: the project directory's name), Stamp (footer text), Prompts (a directory of prompt .mustache sources beside the metadata and templates/), VerifyFile (a verify --format json payload from the Node CLI, for the requirement verdicts), RoutesFile ([{ node, method, path }], node a resolution key). An owned theme under codegen/docs-site/ (assets/explorer.css, assets/explorer.js, templates/explorer-*.mustache) wins over the embedded one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's
Docs view endpoint MetaEndpoint.MetaDocsRoutePath (/_meta/docs), MetaDocsJson(root, routes) and MetaDocs(root, routes) (like /_meta, a helper you mount, not a mount): the body is the docs view of the loaded model alone, byte-identical to every other port's (fixtures/explorer-conformance/model-alone/); MetaDocs builds it once with a strong ETag and Matches(ifNoneMatch) for the 304. Contract: metadata-api.md
Requirement gate + requirement tests Yes (dotnet meta verify, on every run; requirement-tests emits xUnit and is ejectable)
Business-rules gate (ADR-0066, experimental) Yes (dotnet meta verify, on every run; see business rules)
Runtime metadata Loader API + render engine; ObjectManager-style runtime tier on the roadmap

Conformance status

Per-corpus pass counts move every release — see docs/CONFORMANCE.md for the current, authoritative per-port numbers (metamodel, YAML, render, verify, persistence, API contract). C# is green across all six active corpora today.

See also