dotnet/efcore · error · InvalidOperationException

Failed to load project for query precompilation. Project

Error message

Failed to load project for query precompilation. Project: {project}. Error: {error}

What it means

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.

Solutions

  1. Run `dotnet restore` on the project before optimize.
  2. Align the installed .NET SDK with the version the EF tools target (check global.json).
  3. Read the verbose MSBuildWorkspace diagnostics (reported via -v) and fix the listed load errors.
  4. Temporarily disable precompilation (--no-precompile-queries) to isolate whether the project itself loads in the runtime.

Example fix

# before
> dotnet ef dbcontext optimize --precompile-queries

# after
> dotnet restore
> dotnet ef dbcontext optimize --precompile-queries -v
Defensive patterns

Strategy: try-catch

Validate before calling

// verify the project builds standalone before invoking optimize
var psi = new ProcessStartInfo("dotnet", $"build {projectPath}");
if (Process.Start(psi)!.WaitForExit(60_000) is false || Environment.ExitCode != 0)
    throw new InvalidOperationException("Project does not build; fix before optimize.");

Try / catch

try { operations.Optimize(..., precompileQueries: true, ...); }
catch (InvalidOperationException ex)
  when (ex.Message.Contains("Failed to load project"))
{ /* run dotnet restore, align SDK, read diagnostics, then retry */ }

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of dotnet/efcore@3a2006ef56 (2026-08-11). Data as JSON: /api/errors/e6eec88a9f996c13. Report an issue: GitHub.

Appendix: source

Thrown at src/EFCore.Design/Design/Internal/DbContextOperations.cs:361

            workspace.LoadMetadataForReferencedProjects = true;
#pragma warning disable CS0618 // Obsolete
            workspace.WorkspaceFailed += (_, e)
                => _reporter.WriteError(DesignStrings.MSBuildWorkspaceFailure(e.Diagnostic.Kind, e.Diagnostic.Message));
#pragma warning restore CS0618 // Obsolete
            project = workspace.OpenProjectAsync(_project).GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {
            if (workspace != null && !workspace.Diagnostics.IsEmpty)
            {
                var diagnosticMessages = Environment.NewLine
                    + string.Join(
                        Environment.NewLine,
                        workspace.Diagnostics.Select(d => $"  {d.Kind}: {d.Message}"));
                _reporter.WriteVerbose(DesignStrings.MSBuildWorkspaceDiagnostics(diagnosticMessages));
            }

            throw new InvalidOperationException(
                DesignStrings.QueryPrecompilationProjectLoadFailed(_project, ex.Message), ex);
        }

        if (!project.SupportsCompilation)
        {
            throw new NotSupportedException(DesignStrings.UncompilableProject(_project));
        }

        var compilation = project.GetCompilationAsync().GetAwaiter().GetResult()!;
        var errorDiagnostics = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray();
        if (errorDiagnostics.Length != 0)
        {
            var errorBuilder = new StringBuilder();
            errorBuilder.AppendLine(DesignStrings.CompilationErrors);
            foreach (var diagnostic in errorDiagnostics)
            {
                errorBuilder.AppendLine(diagnostic.ToString());
            }

View on GitHub (pinned to 3a2006ef56)