{"record":{"id":"d37d629888c1d501","repo":"dotnet/efcore","slug":"model-building-is-not-supported-when-publishing-wi","errorCode":null,"errorMessage":"Model building is not supported when publishing with NativeAOT. Use a compiled model.","messagePattern":"Model building is not supported when publishing with NativeAOT\\. Use a compiled model\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"src/EFCore.Relational/Metadata/Internal/Column.cs","lineNumber":58,"sourceCode":"    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    public new virtual Table Table\n        => (Table)base.Table;\n\n    /// <summary>\n    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    public virtual ColumnAccessors Accessors\n    {\n        get => NonCapturingLazyInitializer.EnsureInitialized(\n            ref _accessors, this, static column =>\n                RuntimeFeature.IsDynamicCodeSupported\n                    ? ColumnAccessorsFactory.Create(column)\n                    : throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel));\n        set => _accessors = value;\n    }\n\n    /// <summary>\n    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    public override string ToString()\n        => ((IColumn)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);\n\n    /// <inheritdoc />\n    ITable IColumn.Table\n    {\n        [DebuggerStepThrough]\n        get => Table;\n    }","sourceCodeStart":40,"sourceCodeEnd":76,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Metadata/Internal/Column.cs#L40-L76","documentation":"Thrown by Column.Accessors getter when RuntimeFeature.IsDynamicCodeSupported is false — i.e. the app is published with NativeAOT, which forbids the reflection-based accessor generation EF normally does at runtime. Accessing the lazy-initialized ColumnAccessors under AOT would require dynamic code, so EF throws and directs you to a precompiled model.","triggerScenarios":"Publishing an EF Core relational app with PublishAot=true (or PublishReadyToRun with trimming/AOT) without first generating a compiled model. The exception fires the first time the runtime accesses per-column value accessors (typically during query materialization or SaveChanges).","commonSituations":"New .NET 8+ projects enabling NativeAOT for startup/size and forgetting EF needs a compiled model. CI producing AOT images that pass build but fail at first DB call. Upgrading an app to AOT publishing without regenerating the model.","solutions":["Generate a compiled model: run `dotnet ef dbcontext optimize` (or `Optimize-DbContext` in PMC) and wire up the generated *ModelBuilder in OnModelCreating / UseModel.","Remove or disable NativeAOT for this app if a compiled model is not feasible; set PublishAot=false.","Regenerate the compiled model whenever the model changes (treat it as a build step, check in the generated files).","Add a CI check that runs the app's first query under the AOT-published binary to catch regressions."],"exampleFix":"// before\n// csproj:\n<PublishAot>true</PublishAot>\n// DbContext uses normal model building -> throws at runtime\n\n// after\n// 1) dotnet ef dbcontext optimize --output-dir CompiledModel\n// 2) register generated model\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\n    => new CompiledModel().CreateModel(modelBuilder);\n// 3) UseDbContextModel is wired via options.UseModel(new CompiledModel())","handlingStrategy":"validation","validationCode":"// Detect AOT/trimming at startup and refuse to run without a compiled model\nif (!RuntimeFeature.IsDynamicCodeSupported && !typeof(MyDbContext).IsCompiledModelCached())\n{\n    throw new InvalidOperationException(\"Compiled model required under NativeAOT. Run 'dotnet ef dbcontext optimize'.\");\n}","typeGuard":null,"tryCatchPattern":"// Wrap the first DB operation in startup checks\ntry { _ = ctx.Users.First(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"NativeAOT\"))\n{\n    logger.LogCritical(\"Compiled model missing; run 'dotnet ef dbcontext optimize'\");\n    throw;\n}","preventionTips":["Generate the compiled model in the same commit that enables PublishAot.","Add a CI step that publishes the AOT binary and runs one smoke query.","Regenerate the compiled model whenever the model changes and check it in."],"tags":["efcore","nativeaot","compiled-model","runtime","deployment"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}