dotnet/efcore · critical · InvalidOperationException

Model building is not supported when publishing with NativeA

Error message

Model building is not supported when publishing with NativeAOT. Use a compiled model.

What it means

Thrown when EF Core lazily builds the row-key value factory for a unique constraint (UniqueConstraint.GetRowKeyValueFactory) at runtime but dynamic code generation is unavailable because the app was published with NativeAOT. Under AOT, runtime model building/metadata construction is not allowed; EF needs a pre-generated compiled model instead. The guard is `RuntimeFeature.IsDynamicCodeSupported` being false.

Source

Thrown at src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs:93

    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public virtual void SetRowKeyValueFactory(IRowKeyValueFactory factory)
        => _rowKeyValueFactory = factory;

    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public virtual IRowKeyValueFactory GetRowKeyValueFactory()
        => NonCapturingLazyInitializer.EnsureInitialized(
            ref _rowKeyValueFactory, this,
            static constraint =>
                RuntimeFeature.IsDynamicCodeSupported
                    ? constraint.Table.Model.Model.GetRelationalDependencies().RowKeyValueFactoryFactory.Create(constraint)
                    : throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel));

    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public override string ToString()
        => ((IUniqueConstraint)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);

    /// <inheritdoc />
    ITable IUniqueConstraint.Table
        => Table;

    /// <inheritdoc />
    IReadOnlyList<IColumn> IUniqueConstraint.Columns
        => Columns;

View on GitHub (pinned to dbf9771522)

Solutions

  1. Generate a compiled model: run `dotnet ef dbcontext optimize` (or the design-time `dbcontext optimize` command) and wire up `UseCompiledModel` on your DbContext.
  2. Add the generated `*ModelBuilder` partial/configure call so the runtime uses pre-built metadata instead of reflecting.
  3. If AOT is not required, disable `<PublishAot>` / `PublishReadyToRun` so `RuntimeFeature.IsDynamicCodeSupported` is true.
  4. Ensure you are on an EF Core version that supports compiled models and that the compiled model was built against the same model (regenerate after schema/OnModelCreating changes).

Example fix

// before
options.UseSqlServer(connectionString);
// after
dotnet ef dbcontext optimize --output-dir CompiledModels
options.UseSqlServer(connectionString).UseCompiledModel(typeof(MyCompiledModel).Assembly);
Defensive patterns

Strategy: validation

Validate before calling

// Before relying on relational metadata at runtime, confirm AOT posture and compiled model.
if (!System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported)
{
    // Must have generated + registered a compiled model.
    if (options.FindExtension<CoreOptionsExtension>()?.CompiledModel is null)
        throw new InvalidOperationException("Generate and register a compiled model before publishing with NativeAOT.");
}

Prevention

When it happens

Trigger: Calling any code path that reads the row-key value factory of a relational unique constraint (e.g. executing a query/SaveChanges that resolves a unique-key match against a table-mapped entity) in an app published with `<PublishAot>true</PublishAot>` and no compiled model generated via `dotnet ef dbcontext optimize`.

Common situations: Enabling NativeAOT/ReadyToRun trimming on a console or ASP.NET Core app that uses EF Core relational providers; upgrading EF Core to a version that enforces compiled models under AOT; publishing with `dotnet publish -r <rid> /p:PublishAot=true` without first generating the compiled model.

Related errors


AI-assisted analysis of dotnet/efcore@dbf9771522 (2026-08-06). Data as JSON: /api/errors/4e1d6b4061e750a4. Report an issue: GitHub.