{"record":{"id":"e6eec88a9f996c13","repo":"dotnet/efcore","slug":"failed-to-load-project-for-query-precompilation-p","errorCode":null,"errorMessage":"Failed to load project for query precompilation. Project: {project}. Error: {error}","messagePattern":"Failed to load project for query precompilation\\. Project: (.+?)\\. Error: (.+?)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Design/Internal/DbContextOperations.cs","lineNumber":361,"sourceCode":"            workspace.LoadMetadataForReferencedProjects = true;\n#pragma warning disable CS0618 // Obsolete\n            workspace.WorkspaceFailed += (_, e)\n                => _reporter.WriteError(DesignStrings.MSBuildWorkspaceFailure(e.Diagnostic.Kind, e.Diagnostic.Message));\n#pragma warning restore CS0618 // Obsolete\n            project = workspace.OpenProjectAsync(_project).GetAwaiter().GetResult();\n        }\n        catch (Exception ex)\n        {\n            if (workspace != null && !workspace.Diagnostics.IsEmpty)\n            {\n                var diagnosticMessages = Environment.NewLine\n                    + string.Join(\n                        Environment.NewLine,\n                        workspace.Diagnostics.Select(d => $\"  {d.Kind}: {d.Message}\"));\n                _reporter.WriteVerbose(DesignStrings.MSBuildWorkspaceDiagnostics(diagnosticMessages));\n            }\n\n            throw new InvalidOperationException(\n                DesignStrings.QueryPrecompilationProjectLoadFailed(_project, ex.Message), ex);\n        }\n\n        if (!project.SupportsCompilation)\n        {\n            throw new NotSupportedException(DesignStrings.UncompilableProject(_project));\n        }\n\n        var compilation = project.GetCompilationAsync().GetAwaiter().GetResult()!;\n        var errorDiagnostics = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray();\n        if (errorDiagnostics.Length != 0)\n        {\n            var errorBuilder = new StringBuilder();\n            errorBuilder.AppendLine(DesignStrings.CompilationErrors);\n            foreach (var diagnostic in errorDiagnostics)\n            {\n                errorBuilder.AppendLine(diagnostic.ToString());\n            }","sourceCodeStart":343,"sourceCodeEnd":379,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Design/Design/Internal/DbContextOperations.cs#L343-L379","documentation":"InvalidOperationException from DbContextOperations when loading the user's project via MSBuildWorkspace for query precompilation fails. The original exception message and any workspace diagnostics are surfaced; precompilation cannot proceed without a loaded, compilable project.","triggerScenarios":"Enabling precompileQueries during `dotnet ef dbcontext optimize` while the project cannot be loaded by MSBuildWorkspace — mismatched SDK, missing restore, unsupported project format, or a corrupt obj/ bin.","commonSituations":"Using a newer/older .NET SDK than the tooling supports, running without `dotnet restore`, mixing C# language versions, third-party SDK projects, or after upgrading EF tools and .NET SDK out of sync.","solutions":["Run `dotnet restore` on the project before optimize.","Align the installed .NET SDK with the version the EF tools target (check global.json).","Read the verbose MSBuildWorkspace diagnostics (reported via -v) and fix the listed load errors.","Temporarily disable precompilation (--no-precompile-queries) to isolate whether the project itself loads in the runtime."],"exampleFix":"# before\n> dotnet ef dbcontext optimize --precompile-queries\n\n# after\n> dotnet restore\n> dotnet ef dbcontext optimize --precompile-queries -v","handlingStrategy":"try-catch","validationCode":"// verify the project builds standalone before invoking optimize\nvar psi = new ProcessStartInfo(\"dotnet\", $\"build {projectPath}\");\nif (Process.Start(psi)!.WaitForExit(60_000) is false || Environment.ExitCode != 0)\n    throw new InvalidOperationException(\"Project does not build; fix before optimize.\");","typeGuard":null,"tryCatchPattern":"try { operations.Optimize(..., precompileQueries: true, ...); }\ncatch (InvalidOperationException ex)\n  when (ex.Message.Contains(\"Failed to load project\"))\n{ /* run dotnet restore, align SDK, read diagnostics, then retry */ }","preventionTips":["Always `dotnet restore` before running optimize with precompilation.","Keep the .NET SDK aligned (global.json) with what EF tools support.","Run a plain `dotnet build` first to surface environment issues."],"tags":["design-time","ef-tools","precompilation","msbuild","roslyn"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}