{"record":{"id":"4e1d6b4061e750a4","repo":"dotnet/efcore","slug":"model-building-is-not-supported-when-publishing-wi-4e1d6b","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/UniqueConstraint.cs","lineNumber":93,"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 virtual void SetRowKeyValueFactory(IRowKeyValueFactory factory)\n        => _rowKeyValueFactory = factory;\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 IRowKeyValueFactory GetRowKeyValueFactory()\n        => NonCapturingLazyInitializer.EnsureInitialized(\n            ref _rowKeyValueFactory, this,\n            static constraint =>\n                RuntimeFeature.IsDynamicCodeSupported\n                    ? constraint.Table.Model.Model.GetRelationalDependencies().RowKeyValueFactoryFactory.Create(constraint)\n                    : throw new InvalidOperationException(CoreStrings.NativeAotNoCompiledModel));\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        => ((IUniqueConstraint)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);\n\n    /// <inheritdoc />\n    ITable IUniqueConstraint.Table\n        => Table;\n\n    /// <inheritdoc />\n    IReadOnlyList<IColumn> IUniqueConstraint.Columns\n        => Columns;\n","sourceCodeStart":75,"sourceCodeEnd":111,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Metadata/Internal/UniqueConstraint.cs#L75-L111","documentation":"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.","triggerScenarios":"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`.","commonSituations":"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.","solutions":["Generate a compiled model: run `dotnet ef dbcontext optimize` (or the design-time `dbcontext optimize` command) and wire up `UseCompiledModel` on your DbContext.","Add the generated `*ModelBuilder` partial/configure call so the runtime uses pre-built metadata instead of reflecting.","If AOT is not required, disable `<PublishAot>` / `PublishReadyToRun` so `RuntimeFeature.IsDynamicCodeSupported` is true.","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)."],"exampleFix":"// before\noptions.UseSqlServer(connectionString);\n// after\ndotnet ef dbcontext optimize --output-dir CompiledModels\noptions.UseSqlServer(connectionString).UseCompiledModel(typeof(MyCompiledModel).Assembly);","handlingStrategy":"validation","validationCode":"// Before relying on relational metadata at runtime, confirm AOT posture and compiled model.\nif (!System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported)\n{\n    // Must have generated + registered a compiled model.\n    if (options.FindExtension<CoreOptionsExtension>()?.CompiledModel is null)\n        throw new InvalidOperationException(\"Generate and register a compiled model before publishing with NativeAOT.\");\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Run `dotnet ef dbcontext optimize` and call `UseCompiledModel` whenever `<PublishAot>true</PublishAot>` is set.","Regenerate the compiled model after any OnModelCreating change before publishing.","Add a startup assertion checking the compiled model is active when `!RuntimeFeature.IsDynamicCodeSupported`."],"tags":["native-aot","efcore","compiled-model","metadata","relational"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}