{"record":{"id":"27389e64ff45f536","repo":"dotnet/efcore","slug":"the-model-must-be-finalized-and-its-runtime-depend-27389e","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/Infrastructure/RelationalModelExtensions.cs","lineNumber":28,"sourceCode":"/// </summary>\npublic static class RelationalModelExtensions\n{\n    /// <summary>\n    ///     Returns the relational service dependencies.\n    /// </summary>\n    /// <remarks>\n    ///     See <see href=\"https://aka.ms/efcore-docs-providers\">Implementation of database providers and extensions</see>\n    ///     for more information and examples.\n    /// </remarks>\n    /// <param name=\"model\">The model.</param>\n    /// <param name=\"methodName\">The name of the calling method.</param>\n    /// <returns>The relational service dependencies.</returns>\n    public static RelationalModelDependencies GetRelationalDependencies(\n        this IModel model,\n        [CallerMemberName] string methodName = \"\")\n        => (RelationalModelDependencies?)model\n                .FindRuntimeAnnotation(RelationalAnnotationNames.ModelDependencies)?.Value\n            ?? throw new InvalidOperationException(CoreStrings.ModelNotFinalized(methodName));\n}\n","sourceCodeStart":10,"sourceCodeEnd":30,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Infrastructure/RelationalModelExtensions.cs#L10-L30","documentation":"GetRelationalDependencies (RelationalModelExtensions.cs:28) throws CoreStrings.ModelNotFinalized(methodName) when the model lacks the ModelDependencies runtime annotation. That annotation is stamped onto the model only during IModelRuntimeInitializer.Initialize (which finalizes the model and wires runtime services). Requesting relational dependencies earlier - on a not-yet-finalized or manually built IModel - means the runtime services are not present, so the API refuses rather than returning null.","triggerScenarios":"Calling a relational API that internally calls GetRelationalDependencies() on an IModel that came from a stand-alone ModelBuilder without FinalizeModel()+Initialize(), or before OnModelCreating completes, or from a convention running mid-build.","commonSituations":"Provider/tooling code building a model manually with new ModelBuilder() and then using it; querying model metadata inside OnModelCreating before the model is finalized; a custom convention that calls relational extensions too early; caching a non-finalized IModel and reusing it at runtime.","solutions":["Finalize and initialize the model: `var model = ((IModelRuntimeInitializer)serviceProvider.GetService(...)).Initialize modelBuilder.FinalizeModel()` or simply use a built DbContext whose OnModelCreating has completed.","If using a stand-alone ModelBuilder, call IModelRuntimeInitializer.Initialize(modelBuilder.FinalizeModel()) before any runtime query.","Defer the relational-dependency call until after the context has constructed its model (e.g. in a post-build hook rather than a convention)."],"exampleFix":"// before\nvar modelBuilder = new ModelBuilder();\nmodelBuilder.Entity<Blog>();\nvar deps = modelBuilder.Model.GetRelationalDependencies(); // throws - not finalized\n\n// after\nvar model = modelBuilder.FinalizeModel();\nvar initializer = serviceProvider.GetRequiredService<IModelRuntimeInitializer>();\ninitializer.Initialize(model);\nvar deps = model.GetRelationalDependencies();","handlingStrategy":"validation","validationCode":"if (model is not IRuntimeModel { IsReadonly: true } /* or check annotation */)\n{\n    // ensure finalized+initialized before calling GetRelationalDependencies\n    var initializer = serviceProvider.GetRequiredService<IModelRuntimeInitializer>();\n    model = initializer.Initialize(((IModel)model).FinalizeModel() is var f ? f : model);\n}\nvar deps = model.GetRelationalDependencies();","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Always run IModelRuntimeInitializer.Initialize(modelBuilder.FinalizeModel()) for stand-alone models.","Don't call runtime relational APIs inside OnModelCreating or conventions.","Reuse the context's own finalized model for runtime queries rather than a hand-built one."],"tags":["model-finalization","runtime-initializer","metadata","provider"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}