dotnet/efcore · error · InvalidOperationException

Failed to compile migration '{migrationId}'. Errors: {errors

Error message

Failed to compile migration '{migrationId}'. Errors:
{errors}

What it means

CSharpMigrationCompiler.CompileMigration ran Roslyn CSharpCompilation.Emit over the generated migration + metadata + snapshot sources and the emit reported errors. This happens during runtime (in-process) migration compilation used by AddAndApplyMigration. The thrown InvalidOperationException lists each diagnostic; the generated source, references, or model snapshot have a compile error.

Source

Thrown at src/EFCore.Design/Migrations/Design/CSharpMigrationCompiler.cs:95

        // Create the compilation
        var compilation = CSharpCompilation.Create(
            assemblyName,
            syntaxTrees,
            references,
            CompilationOptions);

        // Emit to memory and load
        using var assemblyStream = new MemoryStream();
        var emitResult = compilation.Emit(assemblyStream);

        if (!emitResult.Success)
        {
            var errors = emitResult.Diagnostics
                .Where(d => d.Severity == DiagnosticSeverity.Error)
                .Select(d => d.ToString());

            throw new InvalidOperationException(
                DesignStrings.MigrationCompilationFailed(
                    scaffoldedMigration.MigrationId,
                    string.Join(Environment.NewLine, errors)));
        }

        assemblyStream.Seek(0, SeekOrigin.Begin);
        return AssemblyLoadContext.Default.LoadFromStream(assemblyStream);
    }

    private IReadOnlyList<MetadataReference> GetOrCreateCachedReferences()
        => NonCapturingLazyInitializer.EnsureInitialized(
            ref _cachedReferences,
            this,
            static self =>
            {
                var references = new List<MetadataReference>();

                // Add references from all loaded assemblies (except dynamic/in-memory ones)

View on GitHub (pinned to dbf9771522)

Solutions

  1. Read the diagnostics in the error message -- they name the file (e.g. <MigrationId>.cs) and the CS#### code.
  2. Re-scaffold the migration cleanly (dotnet ef migrations remove then add) to drop hand edits that broke compilation.
  3. Ensure the project and all referenced projects/packages share one EF Core version so references resolve.
  4. If a custom operation type is involved, register a CSharpMigrationOperationGenerator that handles it (see error 199).

Example fix

// before: hand-edited snapshot references a removed type
modelBuilder.Entity<Order>(b => { b.Property<OldStatus>(e => e.Status); });
// after: regenerate after restoring/renaming the type
dotnet ef migrations remove
dotnet ef migrations add FixOrderStatus
Defensive patterns

Strategy: try-catch

Try / catch

try { compiler.CompileMigration(migration, contextType); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Failed to compile migration"))
{ /* log diagnostics, regenerate the migration, verify reference/version consistency */ }

Prevention

When it happens

Trigger: AddAndApplyMigration -> compiler.CompileMigration(migration, contextType) emits a dynamic assembly from the scaffolded code; emitResult.Success is false at line 89. Causes: a custom migration operation/annotation the generator emitted incorrectly, a model snapshot referencing a type not on the reference set, a generated identifier that collides, or stale assembly references.

Common situations: Custom MigrationOperation types not supported by the code generator (see error 199 cascading here); references set missing an assembly the snapshot needs; nullable context mismatch; hand-edited migration/snapshot that no longer compiles; provider version producing scaffolding code incompatible with the loaded references.

Related errors


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