{"record":{"id":"6b1293203a09c3be","repo":"dotnet/efcore","slug":"failed-to-compile-migration-migrationid-error","errorCode":null,"errorMessage":"Failed to compile migration '{migrationId}'. Errors:\n{errors}","messagePattern":"Failed to compile migration '(.+?)'\\. Errors:\n(.+?)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Migrations/Design/CSharpMigrationCompiler.cs","lineNumber":95,"sourceCode":"\n        // Create the compilation\n        var compilation = CSharpCompilation.Create(\n            assemblyName,\n            syntaxTrees,\n            references,\n            CompilationOptions);\n\n        // Emit to memory and load\n        using var assemblyStream = new MemoryStream();\n        var emitResult = compilation.Emit(assemblyStream);\n\n        if (!emitResult.Success)\n        {\n            var errors = emitResult.Diagnostics\n                .Where(d => d.Severity == DiagnosticSeverity.Error)\n                .Select(d => d.ToString());\n\n            throw new InvalidOperationException(\n                DesignStrings.MigrationCompilationFailed(\n                    scaffoldedMigration.MigrationId,\n                    string.Join(Environment.NewLine, errors)));\n        }\n\n        assemblyStream.Seek(0, SeekOrigin.Begin);\n        return AssemblyLoadContext.Default.LoadFromStream(assemblyStream);\n    }\n\n    private IReadOnlyList<MetadataReference> GetOrCreateCachedReferences()\n        => NonCapturingLazyInitializer.EnsureInitialized(\n            ref _cachedReferences,\n            this,\n            static self =>\n            {\n                var references = new List<MetadataReference>();\n\n                // Add references from all loaded assemblies (except dynamic/in-memory ones)","sourceCodeStart":77,"sourceCodeEnd":113,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Design/Migrations/Design/CSharpMigrationCompiler.cs#L77-L113","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Read the diagnostics in the error message -- they name the file (e.g. <MigrationId>.cs) and the CS#### code.","Re-scaffold the migration cleanly (dotnet ef migrations remove then add) to drop hand edits that broke compilation.","Ensure the project and all referenced projects/packages share one EF Core version so references resolve.","If a custom operation type is involved, register a CSharpMigrationOperationGenerator that handles it (see error 199)."],"exampleFix":"// before: hand-edited snapshot references a removed type\nmodelBuilder.Entity<Order>(b => { b.Property<OldStatus>(e => e.Status); });\n// after: regenerate after restoring/renaming the type\ndotnet ef migrations remove\ndotnet ef migrations add FixOrderStatus","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { compiler.CompileMigration(migration, contextType); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Failed to compile migration\"))\n{ /* log diagnostics, regenerate the migration, verify reference/version consistency */ }","preventionTips":["Never hand-edit generated migration/snapshot code in ways that diverge from the model.","Keep EF Core versions uniform across all referenced assemblies.","Re-scaffold (remove + add) after model or provider changes."],"tags":["efcore","migrations","roslyn","compilation","design-time"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}