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 resolves the relational type mapping for a runtime DbFunction's return type (RuntimeDbFunction.TypeMapping) but the app was published with NativeAOT, where `RuntimeFeature.IsDynamicCodeSupported` is false. Runtime type-mapping resolution requires dynamic code, so under AOT a compiled model is mandatory.

Source

Thrown at src/EFCore.Relational/Metadata/RuntimeDbFunction.cs:101

    /// <summary>
    ///     Gets the name of the function in the model.
    /// </summary>
    public virtual string ModelName { get; }

    /// <summary>
    ///     Gets or sets the type mapping for the function's return type.
    /// </summary>
    /// <returns>The type mapping.</returns>
    public virtual RelationalTypeMapping? TypeMapping
    {
        get => _isScalar
            ? NonCapturingLazyInitializer.EnsureInitialized(
                ref _typeMapping, this, static dbFunction =>
                {
                    if (!RuntimeFeature.IsDynamicCodeSupported)
                    {
                        throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel);
                    }

                    var relationalTypeMappingSource =
                        (IRelationalTypeMappingSource)((IModel)dbFunction.Model).GetModelDependencies().TypeMappingSource;
                    return !string.IsNullOrEmpty(dbFunction._storeType)
                        ? relationalTypeMappingSource.FindMapping(dbFunction._returnType, dbFunction._storeType)!
                        : relationalTypeMappingSource.FindMapping(dbFunction._returnType, dbFunction.Model)!;
                })
            : _typeMapping;
        set => _typeMapping = value;
    }

    /// <summary>
    ///     Adds a parameter to the function.
    /// </summary>
    /// <param name="name">The parameter name.</param>
    /// <param name="clrType">The parameter type.</param>
    /// <param name="propagatesNullability">A value which indicates whether the parameter propagates nullability.</param>

View on GitHub (pinned to dbf9771522)

Solutions

  1. Generate and register a compiled model with `dotnet ef dbcontext optimize` + `UseCompiledModel`.
  2. Regenerate the compiled model after adding/changing any DbFunction mapping.
  3. Disable NativeAOT publishing if compiled models are not viable for the project.
  4. Confirm `RuntimeFeature.IsDynamicCodeSupported` in the deployed environment to catch AOT publish misconfiguration early.

Example fix

// before
modelBuilder.HasDbFunction(typeof(MyContext).GetMethod(nameof(MyFunc))!);
options.UseSqlServer(cs);
// after
dotnet ef dbcontext optimize
options.UseSqlServer(cs).UseCompiledModel(typeof(MyCompiledModel).Assembly);
Defensive patterns

Strategy: validation

Validate before calling

if (!System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported
    && options.FindExtension<CoreOptionsExtension>()?.CompiledModel is null)
{
    throw new InvalidOperationException("DbFunction type mapping requires a compiled model under NativeAOT.");
}

Prevention

When it happens

Trigger: Using a mapped DbFunction in a LINQ query under a NativeAOT-published app without a compiled model; any path that reads `.TypeMapping` on a RuntimeDbFunction when dynamic code is not supported.

Common situations: Publishing with `<PublishAot>true</PublishAot>` and referencing DbFunctions in queries; AOT app that worked in Debug (JIT) but fails when published; forgetting to regenerate the compiled model after adding a DbFunction.

Related errors


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