Table of Contents

Migration DDL API — declaring and evolving the content model

This page documents the content-model migration DDL/seed API — the C# surface a MibMigrator migration uses to declare a media type and its fields, declare enums, declare many-to-many relations, and seed content rows. It runs against the datamodel/core DB, as opposed to the metadata DB (pages, components, menus — see Page Creation).

Grounded against MibClient2 · MediaiBox.Core.Database.Model.Migration (the migration DDL namespace), cross-checked against real data-model migrations and a live mib.api DB. If a name is not covered here, verify it against the target repo or a live DB rather than guessing — mib types IMibSeed / mib types IMibDdlQueue list the exact live signatures.

The two usings

using MediaiBox.Core.Database.Model.Migration;   // IMibDdlQueue, IColumnBuilder, AddOrUpdateMediaType / WithAdmField / AddPrimaryKey
using MediaiBox.Core.Database.Model.AdmField;    // AdmFieldType

The extension methods (AddOrUpdateMediaType, WithAdmField, AddPrimaryKey) are declared in the Migration namespace; the implementation ships in MediaiBox.Cms.Api.Database.Migrations.Extensions, which the datamodel/ csproj references.

Declare a media type and its fields

ITableBuilder<T> ddl.AddOrUpdateMediaType(
    string name,                       // the SQL table name, e.g. "TESTE_MOVIES"
    Func<IColumnBuilder, T> columns,   // t => new { COL = t.<Type>(...).WithAdmField(...), ... }
    string title,                      // the human label the CMS shows, e.g. "Teste Movies"
    int? mibindex = null)              // optional explicit MIBINDEX; omit to auto-assign

Call ddl.AddPrimaryKey(name, "ID") afterwards as a separate statement.

Required base columns — every media type MUST declare ID + DATEINS + NAME. mib.api's FieldChecker.VerifyColumnsAsync enforces exactly these three; a missing one hard-500s at render (Column 'NAME' was not found on Media Type X / AdmFieldMisconfigurationException) — including a pure join/bridge or child table where a NAME feels pointless (add it anyway, Varchar, nullable is fine). ID = Int identity PK; DATEINS = UtcDateTime (defaultValueSql: "GETUTCDATE()"); NAME = Varchar. OWNER (Integer) is the conventional 4th (a WARN, not a FieldChecker rule). mib validate <TYPE> catches a missing base column STATICALLY — run it before redeploy rather than discovering it as a live 500.

AddOrUpdateMediaType only CREATEs — it never ALTERs. It always emits CREATE TABLE, so calling it a SECOND time for the same media type (a new migration that re-declares it just to "add a column") fails with There is already an object named 'X' in the database. IMibDdlQueue exposes no AddColumn. To evolve an already-applied type:

  • dev loop (DESTRUCTIVE): mib migration redo <id> --wipe — DROPs the table + its rows, then reapplies the ORIGINAL migration with the new field added. Fine for a sandbox with no real data.
  • additive (data-preserving): a NEW migration that does BOTH — physically ALTER TABLE <T> ADD <COL> … (raw SQL via the migration's IMibSql; IMibDdlQueue has no AddColumn) AND seed.AddOrUpdateAdmField(...) in UpSeed to register the ADM_FIELDS metadata. ⚠ AddOrUpdateAdmField ALONE only writes the metadata row — it does NOT create the column. Skipping the ALTER passes apply-time SILENTLY, then 500s every read (Column X was not found on Media Type Y) — WORSE than the loud CREATE-TABLE failure. mib validate <TYPE> catches the missing column statically.

This builder creates a physical table. A media type can also be backed by a read-only DB view (MIB stores only the object name — no table/view flag): create the view via raw SQL in the migration, then register it in MEDIA_TYPES + ADM_FIELDS (base columns ID/NAME/DATEINS) and mark it read-only with BLOCK_WRITE/BLOCK_DELETE/BLOCK_CREATE. See Media Type.

IColumnBuilder (the t. factories)

Each factory returns a column the anonymous-object value binds to. Chain .WithAdmField(...) to surface it as a CMS field.

Factory Notes
t.Int(...) 32-bit int; identity: true for the PK
t.Long(...) 64-bit
t.Short(...) 16-bit
t.Byte(...) 8-bit
t.Decimal(...) use precision: / scale:
t.Double(...)
t.Single(...)
t.String(...) use maxLength:; unicode: toggles nvarchar/varchar
t.Boolean(...)
t.DateTime(...) use defaultValueSql: "GETUTCDATE()" for DATEINS
t.Time(...)
t.Guid(...)
t.Binary(...)
t.Json(...)
t.Cron(...)

Named optionals (all factories): nullable, identity, maxLength, defaultValue, defaultValueSql, unicode, precision, scale.

.WithAdmField(...) — register the CMS field in the same call

IColumnModel WithAdmField(
    string name,                        // the field label the form/list shows
    AdmFieldType admFieldType,          // picks the widget (see the table below)
    int owner = 1,
    bool readOnly = false,              // non-editable input (base columns are readOnly: true)
    int? enumTypeId = null,             // Enum: the ENUMTYPE id …
    string enumTypeName = null,         // … OR the enum NAME — set ONE for AdmFieldType.Enum (else the page 500s)
    string relatedTableName = null,     // the related media type — set for Related/DropRelated/NullableDropRelated/Owner/Image
    string relatedColumn = null,
    string relatedColumnName = null,
    bool isUnique = false,
    int? orderEdit = null,              // input order in the edit form (form renders by this)
    int? orderList = null,              // list column order; null/negative = hidden by default on a top-level list
    string regex = null,                // client-side validation pattern
    string dropRelatedNullLabel = null,
    string fieldDescription = null);    // shows in `mib datamodel <TYPE>` field descriptions

(A second overload omits the explicit AdmFieldType and infers it — same tail params.)

  • Enum → set enumTypeName: (or enumTypeId:). WITHOUT it the page hard-500s (AdmFieldMisconfigurationException) — mib validate <TYPE> catches this statically before you redeploy. Content rows store the enum VALUE, never its NAME: for the usual numeric values the physical column must be t.Int. From MIB 7.0.0 an enum's VALUE may also be a string (MEDIAIBOX-11883 — the BFF and mib.api read enum values as strings), stored in a t.String column. t.String + seeding the NAME string compiles + passes the metadata checks, then 500s the first search (EntityEnumValueNotFoundException); the NAME is only the API wire/seam contract (see Declare and seed an enum).
  • Related / DropRelated / NullableDropRelated / Owner / Image → set relatedTableName: (the media type it references). Same FieldChecker rule; same mib validate catch. (The OWNER base column is conventionally a plain Integer, not AdmFieldType.Owner.)
  • readOnly: true is SERVER-enforced, not just UI. mib.api's save loop SKIPS read-only fields (and Owner / Progress / RowVersion) for EVERY caller — the BFF form AND a backend component calling ApiClient.PostAsync/PutAsync directly. A client-sent value is silently dropped (ignored, not rejected). So a read-only field is a trustworthy flag to read/guard on from a business rule — but marking a field readOnly to "protect" it also blocks your own trusted code from writing it; to STAMP a field programmatically (a tenant/instance id, a generated slug), do it in a save seam instead, not via readOnly.
  • An ADM DEFAULT_VALUE is not a WithAdmField parameter. The defaultValue: / defaultValueSql: named optionals of a column factory set the column's SQL DEFAULT, which fills an INSERT that leaves the column out and never reaches the form. The value a NEW form starts with is ADM_FIELDS.DEFAULT_VALUE: seed it with seed.AddOrUpdate(x => x.MibObject("ADM_FIELDS", new { COLUMNNAME, MEDIATYPE = x.FindMibIndex("<TYPE>"), DEFAULT_VALUE = "false" }), new[] { "COLUMNNAME", "MEDIATYPE" }). Where each one applies, the text an Enum or a Boolean default must hold, and the form's required rule: What fills an empty field (mib get building-block.field-defaults).

A column WITHOUT .WithAdmField(...) is a plain physical column the CMS does not surface. A media type with NO ADM_FIELDS renders an empty page.

AdmFieldType — the 30 values

The field's AdmFieldType selects the editor widget.

Value Widget / meaning
Varchar single-line text (the NAME base column)
Text multi-line text
Html rich-text / HTML editor
Integer integer input (the ID base column)
Long 64-bit integer input
Float floating-point input
Boolean checkbox
Date date picker
DateTime date-time picker
UtcDateTime UTC date-time (the DATEINS base column)
Time time picker
Enum dropdown backed by an ENUM (ENUMTYPE_ID)
Related relationship picker → pass relatedTableName:
DropRelated drop-down relationship → pass relatedTableName:
NullableDropRelated nullable drop-down relationship → relatedTableName:
Owner owner reference (the OWNER base column)
Source source reference
Image image upload/picker
Link URL/link field
Json JSON field
Cron cron-expression field
ColorPicker color picker
Password masked password input
PasswordPlain plain password variant
Hidden hidden field
Ipv4 IPv4 address field
RowVersion row-version/concurrency token
OsTimezone OS timezone field
Keyword keyword field (see Multi-select several values from an enum)
Progress progress field

Ordinals — the persisted ADM_FIELDS.TYPE int: 1 Varchar · 2 Text · 3 Html · 4 Integer · 5 Date · 6 DateTime · 7 Source · 8 Enum · 9 Related · 10 Password · 11 Boolean · 12 Long · 13 Float · 14 DropRelated · 15 PasswordPlain · 16 Link · 17 Time · 18 Hidden · 19 Ipv4 · 20 UtcDateTime · 21 RowVersion · 22 OsTimezone · 23 Keyword · 24 NullableDropRelated · 25 Owner · 26 Image · 27 Progress · 28 Json · 29 Cron · 30 ColorPicker. mib datamodel <TYPE> decodes these for you.

Changing an existing type — IMibSeed

These live on IMibSeed in UpSeed / DownSeed, NOT in Up(IMibDdlQueue):

seed.AddOrUpdateAdmField("TESTE_MOVIES", …);                 // ADM_FIELDS METADATA ONLY — see the ⚠ above
seed.DeleteMediaType(name, true, true, true, true, true);    // drop a type (cascade flags)
seed.DeleteAdmField(name, "COL");                            // drop the ADM_FIELDS row (not the physical column)

Extend an existing media type (add columns/fields)

NEVER call ddl.AddOrUpdateMediaType(<same type>, …) a second time to add columns. Despite the "OrUpdate" name, on this MIB line it emits an unconditional CREATE TABLE → There is already an object named '<TYPE>' in the database, and the whole migration rolls back. (Live-reproduced; this was a real dead-end — see mib get recipe.extend-existing-media-type.)

To ADD a field to a type declared in an earlier migration, do both in UpSeed, never in Up:

  1. a raw ALTER TABLE … ADD for the physical column(s) via seed.ExecuteQuery(sql, QueryExecutionPoint.EP0_BeforeAll) — IMibDdlQueue has no AddColumn/raw-SQL, so this is the escape hatch, and EP0_BeforeAll runs it before anything references the column. On an already-populated table each added column must be NULL (or carry a DEFAULT);
  2. a paired seed.AddOrUpdateAdmField(type, f => f.<Type>(columnName: "…", …), …) per field — the ADM_FIELDS metadata. columnName MUST match the ALTER above. Metadata alone succeeds silently then 500s every read (Column X not found), so the two always travel together (see the DDL building block).
public override void Up(IMibDdlQueue ddl) { }   // AddOrUpdateMediaType is CREATE-only; nothing to do in Up

public override void UpSeed(IMibSeed seed)
{
    seed.ExecuteQuery(@"
        ALTER TABLE [dbo].[CATALOG_COMMERCIAL_PACKAGES] ADD
            [PRICE_LABEL]    [varchar](500) NULL,
            [IS_PROMOTIONAL] [bit]          NULL;",
        QueryExecutionPoint.EP0_BeforeAll);

    seed.AddOrUpdateAdmField("CATALOG_COMMERCIAL_PACKAGES",
        f => f.Varchar(name: "Price label", columnName: "PRICE_LABEL", readOnly: false, owner: 1,
                    enumTypeId: null, enumTypeName: null, relatedTableName: null, relatedColumn: null,
                    relatedColumnName: null, isUnique: false, orderEdit: 290, orderList: null,
                    regex: null, dropRelatedNullLabel: null),
        f => f.Boolean(name: "Is promotional", columnName: "IS_PROMOTIONAL", readOnly: false, owner: 1,
                    enumTypeId: null, enumTypeName: null, relatedTableName: null, relatedColumn: null,
                    relatedColumnName: null, isUnique: false, orderEdit: 300, orderList: null,
                    regex: null, dropRelatedNullLabel: null));
}

An additive extension needs no enum-ordering split (unless a new field IS an enum — then seed the enum in an EARLIER migration, per Declare and seed an enum) and no new permission grant (the whole-media-type AUTH_PERMISSIONS grant already covers new fields).

Multi-select several values from an enum

To store multiple selected values from an enum on one field, declare it as AdmFieldType.Keyword bound to the enum type (enumTypeName:) — the Keyword field holds several values (comma/JSON), and the widget offers the enum's ADM_ENUMVALUES as options:

.WithAdmField("Target devices", AdmFieldType.Keyword, enumTypeName: "TARGET_DEVICES")   // multi-valued, backed by the enum

This is NOT an ADM_RELATEDS relation — that models a many-to-many to another media type's rows, not an enum's values. Single-select from an enum = AdmFieldType.Enum + enumTypeName:. Multi-select = same enum, AdmFieldType.Keyword instead. If the requirement is to select several rows of ANOTHER media type (not an enum), that's a many-to-many via ADM_RELATEDS — see Declare a many-to-many relation.

A Keyword field tolerates an enum not yet linked at field-creation time; a single Enum field does NOT — see the ordering trap under Declare and seed an enum.

Exclude or hide an enum value

An Enum field's selectable options ARE the enum's ADM_ENUMVALUES rows.

  • Drop a value EVERYWHERE: remove it from the enum (ADM_ENUMVALUES) in a datamodel migration — every field using this enum loses it.
  • Hide a value for ONE field while other fields keep it: there is no confirmed declarative seam on 7.0 — verified absent (no enum-option filter in ContributeSchema / FormSchemaBuilder / ListSchemaBuilder). Model it differently instead: a SEPARATE enum with just the allowed values, or a Related field to a lookup table you can scope. Do not fabricate a ContributeSchema enum-value filter — it does not exist on 7.0.

Declare and seed an enum

An AdmFieldType.Enum field references an enum type BY NAME (enumTypeName:), so the enum must already exist. Declare + seed it in UpSeed with the vendored seed.AddOrUpdateEnum(...) (in database/Extensions/EnumHelper.cs, shipped by the greenfield scaffold — same vendored-per-repo pattern as AddOrUpdatePage):

public override void UpSeed(IMibSeed seed) =>
    seed.AddOrUpdateEnum(new EnumType {
        Name = "TARGET_DEVICES",                              // == the field's enumTypeName:
        Values = new List<EnumValue> {
            new EnumValue { Name = "Mobile", Value = 1, Order = 0 },
            new EnumValue { Name = "TV",     Value = 2, Order = 1 },
            new EnumValue { Name = "Web",    Value = 3, Order = 2 },
        }
    });

public override void DownSeed(IMibSeed seed) => seed.DeleteEnum("TARGET_DEVICES", alsoDeleteValues: true);
  • Tables: ADM_ENUMTYPES { NAME (unique), OWNER } + ADM_ENUMVALUES { ENUMTYPE_ID, NAME, VALUE (int), MIB_ORDER, OWNER }.
  • Idempotent — the type is upserted unique by NAME, each value by (NAME, ENUMTYPE_ID), so mib migration redo re-runs cleanly.
  • Link the field: .WithAdmField("Target devices", AdmFieldType.Enum, enumTypeName: "TARGET_DEVICES"). Without a matching enum the page 500s — mib validate <TYPE> catches it. (DeleteEnumValue(name, value) drops one value.)
  • Value = the persisted int; Name = the display label and what a validator/save seam RECEIVES — an Enum field's value arrives as the NAME string (e.g. "Home"), never the int. Enum value names are NOT {DICT:}-translatable (only the field label is).
  • ⚠ The PHYSICAL column is t.Int and stores the numeric VALUE — the NAME string is only the API/seam wire contract above. Declaring the column t.String(...) and/or seeding the NAME (e.g. PAGE_TYPE = "Static") in a migration's own content-row seed compiles clean and passes the metadata checks, then 500s the first live search/read (EntityEnumValueNotFoundException). Seed the numeric VALUE (PAGE_TYPE = 1). A fresh mib export --datamodel + mib validate <TYPE> flags a string-typed column behind an Enum AdmField statically; already applied → fix via a new migration (or mib migration redo <id> --wipe pre-prod).
  • Enum vs a Related lookup type is a MODELING CHOICE: an Enum is a fixed, closed list editors cannot extend; a lookup media type + Related field makes the list CONTENT (editors manage rows, relatable, per-row perms). Pick by who maintains the list — don't assume a spec's "multi-select" implies either one.

⚠ Ordering trap (the #1 Enum 500)

AddOrUpdateEnum is an IMibSeed extension, so it runs in UpSeed — which executes AFTER Up, where WithAdmField(enumTypeName:) resolves the name and stamps ADM_FIELDS.ENUMTYPE_ID. Co-locating the enum + the Enum field in ONE migration therefore leaves ENUMTYPE_ID NULL → the page 500s ("has Type configured as Enum, but has no Enum Type associated with it"). Seed the enum in a migration that runs BEFORE the one declaring the field. (An AdmFieldType.Keyword + enumTypeName: field tolerates a not-yet-linked enum; a single AdmFieldType.Enum does not.)

Declare a many-to-many relation

Hard rule: an N:N relation is ALWAYS a relationship table — NEVER LinkObject. This is a non-negotiable authoring rule for the platform (see recipe.hard-rules — mib get recipe.hard-rules).

A .WithAdmField(..., AdmFieldType.Related) field is only the UI picker — it does NOT declare the relation. The relation itself is a row in ADM_RELATEDS, declared in UpSeed with the package helper AdmRelatedHelper.AddOrUpdateAdmRelated(this IMibSeed, AdmRelated) (namespace MediaiBox.Cms.Api.Database.Migrations.Extensions, verified public in 7.0.0-beta8). Do NOT use a named-param seed._UpdateAdmRelateds(...) helper — that is a NON-package vendored wrapper a greenfield does not ship.

AddOrUpdateAdmRelated writes ONLY the ADM_RELATEDS metadata row — the physical relationship table is not auto-created; declare it as a MEDIA TYPE (AddOrUpdateMediaType, the stock pattern) in Up() first, else a live GET 500s Invalid object name '<table>'. The relation is saved as INSERT (local, remote[, order]) only, so every OTHER column on the join table must be identity/defaulted/nullable — the FK columns themselves are plain Integer readOnly (the Related picker belongs on the PARENT type, not the join table).

using MediaiBox.Core.Database.Model.Migration;                // AddOrUpdateMediaType, AddPrimaryKey, AddForeignKey
using MediaiBox.Core.Database.Model.AdmField;                  // AdmFieldType
using MediaiBox.Cms.Api.Database.Migrations.Extensions;        // AdmRelatedHelper, AdmRelated

// Up (DDL) runs BEFORE UpSeed, so one migration can carry both halves; both endpoint types must already exist.
public override void Up(IMibDdlQueue ddl)
{
    ddl.AddOrUpdateMediaType("GVP_MOVIES_GENRES", t => new {
        ID = t.Int(identity: true, nullable: false).WithAdmField("ID", AdmFieldType.Integer, readOnly: true),
        DATEINS = t.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()").WithAdmField("Dateins", AdmFieldType.UtcDateTime, readOnly: true),
        OWNER = t.Int(nullable: false, defaultValue: 1).WithAdmField("Owner", AdmFieldType.Integer, readOnly: true),
        NAME = t.String(nullable: false, maxLength: 250, defaultValue: "").WithAdmField("Name", AdmFieldType.Varchar, readOnly: true),
        MOVIE_ID = t.Int(nullable: false).WithAdmField("Movie", AdmFieldType.Integer, readOnly: true),   // == AdmRelated.LocalColumn
        GENRE_ID = t.Int(nullable: false).WithAdmField("Genre", AdmFieldType.Integer, readOnly: true),   // == AdmRelated.RemoteColumn
        // ORDERED variant ONLY (== AdmRelated.OrderColumn; omit for a plain N:N):
        // ORDER_INDEX = t.Int(nullable: false, defaultValue: 0).WithAdmField("Order", AdmFieldType.Integer, readOnly: true),
    }, "Movies Genres");
    ddl.AddPrimaryKey("GVP_MOVIES_GENRES", "ID");
    ddl.AddForeignKey("GVP_MOVIES_GENRES", "MOVIE_ID", "GVP_MOVIES", "ID", cascadeDelete: true);
    ddl.AddForeignKey("GVP_MOVIES_GENRES", "GENRE_ID", "GVP_GENRES", "ID", cascadeDelete: true);
}

public override void UpSeed(IMibSeed seed) =>
    seed.AddOrUpdateAdmRelated(new AdmRelated {
        Name = "Movies_Genres", LocalTable = "GVP_MOVIES", RemoteTable = "GVP_GENRES",
        LocalColumn = "MOVIE_ID", RemoteColumn = "GENRE_ID",
        IsRelationshipTable = true, RelationshipTable = "GVP_MOVIES_GENRES",   // the join media type
        CopyType = CopyType.UseSameIDs,
    });

public override void DownSeed(IMibSeed seed) =>
    seed.DeleteAdmRelated("GVP_MOVIES", "GVP_GENRES", isLinkObject: false);
  • AdmRelated properties: Name, LocalTable, RemoteTable, LocalColumn, RemoteColumn, LinkObject (bool — legacy; never set it, hard rule), Title, ListView (bool), LinkUnidirectional (bool?), IsRelationshipTable (bool?), RelationshipTable, ForeignKeyType (ForeignKey), RemoveButtonBehaviorType (RemoveButtonBehavior), CopyType (CopyType), OrderColumn.
  • LocalColumn/RemoteColumn name the FK columns IN the RelationshipTable that point at LocalTable/RemoteTable — load-bearing; they must match the join table's real columns. OrderColumn = the join-table column holding display order; set it ONLY for an ORDERED relation an ordered related-list reads (omit for a plain N:N).
  • No auto-mirror: the reverse direction (e.g. "which PAGEs use this ROW" when you only declared PAGE→ROW) needs its OWN AddOrUpdateAdmRelated row with Local/Remote swapped — it may reuse the same physical RelationshipTable.
  • Self-referential / hierarchical relations ARE supported — LocalTable == RemoteTable (a content TREE via a PARENT_ID self-Related, unbounded depth). That is a DATA tree; media-type INHERITANCE is the separate PARENT_MEDIA_TYPE / extends, not an ADM_RELATEDS row.
  • Delete: seed.DeleteAdmRelated(localTable, remoteTable, isLinkObject).
  • If non-admin groups use the relation, seed group permissions on the join media type too.

Seed content rows

To seed actual content rows (not schema), use IMibSeed in UpSeed:

public override void UpSeed(IMibSeed seed) =>
    seed.Insert("GVP_SPORTS_MD_COUNTRIES", new {
        OWNER = 1, SOURCE = 1, NAME = "Chile", COUNTRY_CODE = "CHL"
    }, QueryExecutionPoint.EP7_AfterAll);          // order the statement; AfterAll so referenced rows exist
  • Idempotent upsert: seed.AddOrUpdate<T>(query, keyExpression) matches on the key field(s) so a re-run doesn't duplicate (plain Insert always inserts; Update<T>(query, id) targets a known id). Run mib types IMibSeed for the exact overload shape rather than guessing — there is no AddOrUpdateContent() and no ExecuteSql(); a hallucinated seed API is a CS1061 caught only at deploy-time dotnet build.
  • Execution point: the trailing QueryExecutionPoint (EP0_BeforeAll … EP7_AfterAll) orders the statement — use EP7_AfterAll so referenced rows (the OWNER user, related rows) exist first.
  • SOURCE is nullable — omit it (or seed SOURCE = null) for an UNRESTRICTED, globally-visible row; there is no NOT-NULL / forced default on a Source column, and NULL/0 = no source scope.
  • There is no per-tenant content seed. Content rows carry OWNER (a user id), not an instance — tenancy scopes users/groups + permissions, not content, and migrations run before instances exist. For per-instance content, add your own INSTANCE_ID column and seed/filter it yourself.
  • ⚠ Never hardcode a literal ID from a failed run — IDENTITY values burn across rollbacks. SQL Server keeps incrementing a table's IDENTITY counter even when the seeding transaction ROLLS BACK, so each failed mib redeploy attempt consumes ids: the migrator's "New ID: N" log lines from a failed/retried run go stale, and the finally-committed rows land at HIGHER ids. Re-read the real id by NAME (or another seeded natural key) — mib client search <listPage> "NAME Equal <seeded name>" / a SELECT — before wiring anything (a fixture, a config value, a test) to it.
  • ⚠ MEDIA_TYPES.ID ≠ MIBINDEX — join and grant by MIBINDEX, never by ID. Identity burn makes the two drift apart on any stack that retried a migration (live example: PAGE landed at ID=1097 but MIBINDEX=118). Everything field- and permission-level keys on MIBINDEX: ADM_FIELDS.MEDIATYPE holds the MIBINDEX (a JOIN … ON MEDIA_TYPES.ID silently returns 0 rows), and AUTH_PERMISSIONS media-type grant keys are mediatype_<MIBINDEX>. When diagnosing with raw SQL, resolve the type via SELECT MIBINDEX FROM MEDIA_TYPES WHERE NAME='<TYPE>' first.

Migration ids & ordering

Migration ids (<timestamp>_<Name>) are unique + ordered per project (ContextKey) — NOT globally. The datamodel and metadata projects each track their own applied ids (keyed by (MigrationId, ContextKey)), so two projects can reuse the same timestamp safely. Within one project, ids must be unique and apply in numeric-prefix order.

Helper provenance — package vs scaffold-vendored vs absent

A seed/DDL helper comes from one of three places, and a sample that compiles in one repo may not resolve in another — a customization compiles against the NuGet PACKAGES, which differ from platform SOURCE:

  • Package — always available. Content-model + row API in MediaiBox.Cms.Api.Database.Migrations.Extensions: AddOrUpdateAdmField, AddOrUpdateAdmRelated, AddOrUpdateEnum, AddOrUpdateFileExtension, AddOrIgnoreAdmField, AddContentCriteria, DeleteAdmField/DeleteAdmRelated/DeleteEnum/DeleteEnumValue; plus core IMibSeed (Insert, Update, AddOrUpdate) and the DDL builder (AddOrUpdateMediaType, WithAdmField, AddPrimaryKey).
  • Scaffold-vendored, metadata side — shipped in the greenfield's database/Extensions/. Page/component/template/menu registration: AddOrUpdatePage, AddOrUpdateComponent, AddOrUpdateTemplate, AddOrUpdateTemplateComponent, AddOrUpdateMenuItem, AddOrUpdatePageConfiguration, AddOrUpdatePageComponentConfiguration (+ Delete*). These are per-repo VENDORED source — present in the scaffold; confirm with ls database/Extensions/ (another repo may differ).
  • Not shipped by a greenfield — datamodel-side vendored. Leading-underscore helpers like _UpdateAdmRelateds, _SetMediaTypeGroupPermission, _DeleteAdmRelation are per-repo VENDORED convenience (a private data-model repo's datamodel/Tools/SeedExtensions.cs) — a greenfield does NOT have them. Use the package AddOrUpdateAdmRelated for the ADM_RELATEDS row, model an N:N as a relationship table (a join media type) — never LinkObject — and grant permissions via raw SQL.

A seed._Xxx (leading-underscore) helper is a per-repo VENDORED convenience: grep -r <Helper> database/Extensions/ datamodel/ in the target repo before trusting the exact name; prefer the package API.

System-table quick reference (raw-SQL seeds)

The columns a raw-SQL seed touches — so you don't have to guess them:

Table Columns you'll reference
MEDIA_TYPES MIBINDEX (the numeric id — PERMISSION_KEY = 'mediatype_' + MIBINDEX, ADM_RELATEDS.LOCALTABLE/REMOTETABLE), NAME, TITLE, PARENT_MEDIA_TYPE, BLOCK_WRITE/BLOCK_DELETE/BLOCK_CREATE
ADM_FIELDS MEDIATYPE (MIBINDEX), COLUMNNAME, NAME, TYPE (the AdmFieldType ordinal), READONLY, ENUMTYPE_ID, RELATEDTABLE
AUTH_PERMISSIONS PERMISSION_KEY, DATA (json), DATA_TYPE, RESOURCE_OWNER_ID, RESOURCE_OWNER_TYPE (⚠ deployment-specific), API_CLIENT_ID

You rarely need raw SQL to look up a MIBINDEX — mib datamodel <TYPE> --json already carries mibindex per media type, and a migration can subquery (SELECT MIBINDEX FROM MEDIA_TYPES WHERE NAME = '<TYPE>').

Apply

mib redeploy datamodel        # or run-datamodel-migrations.sh
mib validate <TYPE>           # static FieldChecker — missing enumType/relatedTable/base columns, offline
mib validate <TYPE> --live    # the RUNNING FieldChecker — also catches a Related field whose physical column doesn't exist