{"record":{"id":"66cf38312d2db301","repo":"dotnet/efcore","slug":"unable-to-create-a-dbcontext-of-type-contextty","errorCode":null,"errorMessage":"Unable to create a 'DbContext' of type '{contextType}'. The exception '{rootException}' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728","messagePattern":"Unable to create a 'DbContext' of type '(.+?)'\\. The exception '(.+?)' was thrown while attempting to create an instance\\. For the different patterns supported at design time, see https://go\\.microsoft\\.com/fwlink/\\?linkid=851728","errorType":"exception","errorClass":"OperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Design/Design/Internal/DbContextOperations.cs","lineNumber":544,"sourceCode":"        try\n        {\n            var context = factory();\n            contextType = context.GetType().ShortDisplayName();\n            _reporter.WriteVerbose(DesignStrings.UseContext(contextType));\n\n            var loggerFactory = context.GetService<ILoggerFactory>();\n            loggerFactory.AddProvider(new OperationLoggerProvider(_reporter));\n\n            return context;\n        }\n        catch (Exception ex)\n        {\n            if (ex is TargetInvocationException)\n            {\n                ex = ex.InnerException!;\n            }\n\n            throw new OperationException(\n                DesignStrings.CannotCreateContextInstance(\n                    contextType ?? contextPair.Key.ShortDisplayName(), ex.Message), ex);\n        }\n    }\n\n    /// <summary>\n    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    public virtual IEnumerable<Type> GetContextTypes()\n        => FindContextTypes().Keys;\n\n    /// <summary>\n    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that","sourceCodeStart":526,"sourceCodeEnd":562,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Design/Design/Internal/DbContextOperations.cs#L526-L562","documentation":"Thrown as OperationException by DbContextOperations.CreateContext when the factory/constructor used to instantiate the DbContext throws. The original exception is unwrapped (TargetInvocationException inner is extracted) and its message is embedded, pointing the user to the design-time context-creation patterns documentation. This is the catch-all for any failure while building a DbContext instance at design time.","triggerScenarios":"Running any EF tool that needs a live DbContext instance when the context's constructor, OnConfiguring, or OnModelCreating throws. Sources include IDesignTimeDbContextFactory.CreateDbContext, the service-provider factory path, or ActivatorUtilities.CreateInstance. Examples: missing configuration, invalid connection string, a constructor that resolves an unregistered service, or code that assumes a hosting environment.","commonSituations":"The context's parameterless/parametrized constructor depends on IConfiguration or IHostEnvironment that is not set up at design time. OnConfiguring reads a null configuration value. A design-time factory returns a context whose provider/connection is misconfigured. Missing environment variables. The startup project throws during Program.cs/ConfigureServices execution.","solutions":["Implement IDesignTimeDbContextFactory<TContext> to construct the context with explicit, design-time-safe configuration.","Inspect the wrapped exception message (shown in the error) to find the root cause and fix it (e.g., supply the missing config value).","Ensure OnConfiguring and OnModelCreating do not throw under design-time conditions (EF.IsDesignTime is true).","Verify the --startup-project builds and runs without throwing during service registration."],"exampleFix":"// before - context constructor throws at design time (no IConfiguration)\npublic class AppDbContext : DbContext\n{\n    public AppDbContext(IConfiguration cfg) : base()\n        => Connection = cfg.GetConnectionString(\"Default\"); // null at design time\n}\n\n// after - add a design-time factory\npublic class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>\n{\n    public AppDbContext CreateDbContext(string[] args)\n    {\n        var opts = new DbContextOptionsBuilder<AppDbContext>()\n            .UseSqlServer(\"Server=.;Database=App;Trusted_Connection=True\");\n        return new AppDbContext(opts.Options);\n    }\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { var ctx = ops.CreateContext(contextType); }\ncatch (OperationException ex) when (ex.Message.Contains(\"Unable to create a 'DbContext'\"))\n{\n    // inspect ex.InnerException for the root cause; add/fix an IDesignTimeDbContextFactory\n}","preventionTips":["Implement IDesignTimeDbContextFactory<TContext> so context creation does not depend on the host.","Keep OnConfiguring/OnModelCreating safe under design-time conditions (EF.IsDesignTime).","Ensure the startup project builds and registers services without throwing.","Supply all required configuration in all environments."],"tags":["design","ef-tools","dbcontext","design-time","factory"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}