{"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/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Design/Design/Internal/DbContextOperations.cs#L526-L562","documentation":"OperationException wrapping the real exception thrown while constructing a DbContext instance at design time. The factory delegate (parameterless ctor, IDesignTimeDbContextFactory, or IDbContextFactory via the service provider) threw; the message includes the context type and the inner exception message.","triggerScenarios":"Any design-time command (migrations, optimize, drop) that needs an instance, when OnConfiguring/OnModelCreating/ctor throws — e.g. malformed connection string, missing environment variable, DI registration missing, or a config section that does not exist at design time.","commonSituations":"DbContext reads IConfiguration/ConnectionString at construction but the design-time host has no such config; an IDesignTimeDbContextFactory is missing; environment variables present at runtime are absent when the tools run; a constructor performs network or filesystem work.","solutions":["Read the wrapped inner exception message — it states the true cause (e.g. connection string null).","Add an IDesignTimeDbContextFactory<TContext> for the context so design-time construction does not depend on app config.","Ensure any environment variables/secrets the ctor needs are available to the tool process.","Avoid side effects (file/network/config access) in the DbContext constructor or OnConfiguring."],"exampleFix":"// before - context ctor depends on runtime config unavailable at design time\npublic AppCtx(IConfiguration cfg)\n    : base(cfg.GetConnectionString(\"Db\")!) {}\n\n// after - add a design-time factory\npublic class AppCtxFactory : IDesignTimeDbContextFactory<AppCtx>\n{\n    public AppCtx CreateDbContext(string[] args)\n        => new(new DbContextOptionsBuilder<AppCtx>()\n            .UseSqlServer(\"Server=(localdb)\\\\mssqllocaldb;Database=Design;Trusted_Connection=True;\")\n            .Options);\n}","handlingStrategy":"try-catch","validationCode":"// validate context can be constructed before running heavy design-time work\nusing var probe = Activator.CreateInstance(typeof(AppCtx), designOptions) as DbContext;\nif (probe is null) throw new InvalidOperationException(\"Cannot construct AppCtx.\");","typeGuard":null,"tryCatchPattern":"try { operations.CreateContext(contextType); }\ncatch (OperationException ex) when (ex.Message.Contains(\"Unable to create a 'DbContext'\"))\n{ /* ex.InnerException holds the real cause — fix config/ctor/factory accordingly */ }","preventionTips":["Add an IDesignTimeDbContextFactory<T> so construction does not depend on app config.","Keep DbContext constructors free of network/filesystem/config side effects.","Make design-time environment (env vars, secrets) match runtime needs."],"tags":["design-time","ef-tools","context-discovery","instance-creation"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}