{"record":{"id":"a4ee50e8a43b5642","repo":"dotnet/efcore","slug":"the-model-must-be-finalized-and-its-runtime-depend","errorCode":null,"errorMessage":"The model must be finalized and its runtime dependencies must be initialized before '{method}' can be used. Ensure that either 'OnModelCreating' has completed or, if using a stand-alone 'ModelBuilder', that 'IModelRuntimeInitializer.Initialize(model.FinalizeModel())' was called.","messagePattern":"The model must be finalized and its runtime dependencies must be initialized before '(.+?)' can be used\\. Ensure that either 'OnModelCreating' has completed or, if using a stand-alone 'ModelBuilder', that 'IModelRuntimeInitializer\\.Initialize\\(model\\.FinalizeModel\\(\\)\\)' was called\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Extensions/RelationalModelExtensions.cs","lineNumber":74,"sourceCode":"    /// <returns>The configuration source for the default schema.</returns>\n    public static ConfigurationSource? GetDefaultSchemaConfigurationSource(this IConventionModel model)\n        => model.FindAnnotation(RelationalAnnotationNames.DefaultSchema)?.GetConfigurationSource();\n\n    #endregion Default schema\n\n    /// <summary>\n    ///     Returns the database model.\n    /// </summary>\n    /// <param name=\"model\">The model to get the database model for.</param>\n    /// <returns>The database model.</returns>\n    public static IRelationalModel GetRelationalModel(this IModel model)\n    {\n        var relationalModel = (IRelationalModel?)model.FindRuntimeAnnotationValue(RelationalAnnotationNames.RelationalModel);\n        if (relationalModel == null)\n        {\n            var relationalModelFactory = (Func<IRelationalModel>?)model.FindRuntimeAnnotationValue(\n                    RelationalAnnotationNames.RelationalModelFactory)\n                ?? throw new InvalidOperationException(CoreStrings.ModelNotFinalized(nameof(GetRelationalModel)));\n            lock (relationalModelFactory)\n            {\n                relationalModel = model.GetOrAddRuntimeAnnotationValue(\n                    RelationalAnnotationNames.RelationalModel, f => f!(), relationalModelFactory);\n                model.RemoveRuntimeAnnotation(RelationalAnnotationNames.RelationalModelFactory);\n            }\n        }\n\n        return relationalModel;\n    }\n\n    #region Max identifier length\n\n    /// <summary>\n    ///     Returns the maximum length allowed for store identifiers.\n    /// </summary>\n    /// <param name=\"model\">The model to get the maximum identifier length for.</param>\n    /// <returns>The maximum identifier length.</returns>","sourceCodeStart":56,"sourceCodeEnd":92,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Extensions/RelationalModelExtensions.cs#L56-L92","documentation":"IModel.GetRelationalModel() builds the relational mapping only after the model is finalized and its runtime initializer has attached the RelationalModelFactory runtime annotation (RelationalModelExtensions.cs:74, CoreStrings.ModelNotFinalized). On a raw, unfinalized IModel the factory annotation is absent, so the call cannot proceed.","triggerScenarios":"Calling model.GetRelationalModel() on an IModel from an un-finalized standalone ModelBuilder, or before DbContext.OnModelCreating completes; using a cached/partially-built model in a provider that expects the runtime model.","commonSituations":"Unit tests that build a ModelBuilder, configure entities, then immediately call GetRelationalModel() without finalizing; tooling that reads the relational model from a ModelBuilder.Model snapshot before FinalizeModel().","solutions":["Finalize + initialize: var finalized = modelBuilder.FinalizeModel(); var runtime = serviceProvider.GetService<IModelRuntimeInitializer>()!.Initialize(finalized); then call GetRelationalModel() on the runtime model.","In app code, get the model from a constructed DbContext (dbContext.Model) — it is already runtime-initialized.","If using a design-time context, ensure its OnModelCreating has run before accessing GetRelationalModel()."],"exampleFix":"// before\nvar mb = new ModelBuilder();\nmb.Entity<Order>();\nvar rel = mb.Model.GetRelationalModel();   // throws: not finalized\n\n// after\nvar finalized = mb.FinalizeModel();\nvar initializer = ctx.GetService<IModelRuntimeInitializer>();\nvar runtime = initializer.Initialize(finalized);\nvar rel = runtime.GetRelationalModel();","handlingStrategy":"validation","validationCode":"// Ensure the model is finalized + runtime-initialized before GetRelationalModel.\nvar finalized = modelBuilder.FinalizeModel();\nvar initializer = scope.ServiceProvider.GetRequiredService<IModelRuntimeInitializer>();\nvar runtime = initializer.Initialize(finalized);\nvar rel = runtime.GetRelationalModel();","typeGuard":null,"tryCatchPattern":null,"preventionTips":["In app code, read relational metadata from a constructed DbContext.Model.","In tests, always call FinalizeModel + IModelRuntimeInitializer.Initialize before GetRelationalModel.","Never reuse a partially-built ModelBuilder.Model for relational queries."],"tags":["model-finalization","relational-model","runtime-initialization","metadata"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}