dotnet/efcore · error · InvalidOperationException

Failed to load project for query precompilation. Project: {p

Error message

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

What it means

Thrown by DbContextOperations.PrecompileQueries when workspace.OpenProjectAsync fails for the project being optimized. The exception wraps the original error and, when available, includes MSBuild workspace diagnostics. Query precompilation requires loading the project via Roslyn's MSBuildWorkspace, so any MSBuild/SDK load failure surfaces here.

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 dbf9771522)

Solutions

  1. Run 'dotnet restore' on the project before optimizing, then retry.
  2. Ensure the .NET SDK and a compatible MSBuild are installed and on PATH (run 'dotnet --info').
  3. Clean build artifacts ('dotnet clean') and retry.
  4. Read the wrapped exception message and workspace diagnostics (emitted at verbose level) for the specific MSBuild error and resolve it.
  5. Verify the project file is valid and all package references restore successfully.

Example fix

// before
dotnet ef dbcontext optimize --precompile-queries  // project load fails

// after - restore and clean first
dotnet restore
dotnet clean
dotnet ef dbcontext optimize --precompile-queries --verbose
Defensive patterns

Strategy: try-catch

Try / catch

try { ops.Optimize(..., precompileQueries: true, ...); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Failed to load project for query precompilation"))
{
    // run 'dotnet restore' / 'dotnet clean', check MSBuild availability, then retry
}

Prevention

When it happens

Trigger: Running 'dotnet ef dbcontext optimize --precompile-queries' (or the EF Core precompilation flow) when MSBuildWorkspace cannot open the project file. Root causes include missing/incorrect MSBuild, project SDK issues, broken project references, or required restore not run.

Common situations: Running the EF tools in an environment where MSBuild is not on PATH or the wrong MSBuild is found. Project references a package/SDK that is not restored. Building on a machine without the .NET SDK or with an incompatible version. Corrupted obj/bin artifacts. The project uses a target framework MSBuildWorkspace cannot evaluate.

Related errors


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