dotnet/efcore · error · InvalidOperationException

Compilation failed with errors:

Error message

Compilation failed with errors:

What it means

InvalidOperationException thrown after the project compiles in Roslyn but GetCompilationAsync returns diagnostics with Severity == Error. The error messages from each diagnostic are appended. Precompilation is aborted because the source does not compile.

Solutions

  1. Build the project with `dotnet build` and resolve every error first.
  2. Restore packages (`dotnet restore`) so missing references resolve.
  3. Clean stale artifacts: `dotnet clean` then retry.
  4. Read each diagnostic in the thrown message and fix at its source location.

Example fix

# before
> dotnet ef dbcontext optimize --precompile-queries   # fails on CS errors

# after
> dotnet build src/MyApp.Data
# fix any errors reported, then
> dotnet ef dbcontext optimize --precompile-queries
Defensive patterns

Strategy: validation

Validate before calling

// ensure the project compiles with zero errors before optimize
if (await Process.RunAsync("dotnet", $"build {projectPath} --no-restore") != 0)
    throw new InvalidOperationException("Project has compile errors; resolve before optimize.");

Try / catch

try { operations.Optimize(..., precompileQueries: true, ...); }
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Compilation failed"))
{ /* each diagnostic in ex.Message must be fixed at its source */ }

Prevention

When it happens

Trigger: Running `dotnet ef dbcontext optimize --precompile-queries` against a project that has C# compile errors (missing references, syntax errors, type errors). The errors are reported before any query code is generated.

Common situations: Pending compile errors in the working tree, missing package references that the IDE tolerates but the command-line compiler rejects, wrong target framework, or a stale obj/ from a previous build.

Related errors


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

Appendix: source

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

        }

        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());
            }

            throw new InvalidOperationException(errorBuilder.ToString());
        }

        var syntaxGenerator = SyntaxGenerator.GetGenerator(
            workspace, _language == "VB" ? LanguageNames.VisualBasic : _language ?? LanguageNames.CSharp);

        var precompiledQueryCodeGenerator = services.GetRequiredService<IPrecompiledQueryCodeGeneratorSelector>().Select(_language);

        var precompilationErrors = new List<PrecompiledQueryCodeGenerator.QueryPrecompilationError>();
        var generatedFiles = precompiledQueryCodeGenerator.GeneratePrecompiledQueries(
            compilation,
            syntaxGenerator,
            context,
            memberAccessReplacements,
            precompilationErrors,
            generatedFileNames,
            assembly: _assembly,
            suffix);

View on GitHub (pinned to 3a2006ef56)