dotnet/efcore · error · OperationException
Unable to create a 'DbContext' of type '{contextType}'. The
Error message
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 What it means
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.
Source
Thrown at src/EFCore.Design/Design/Internal/DbContextOperations.cs:544
try
{
var context = factory();
contextType = context.GetType().ShortDisplayName();
_reporter.WriteVerbose(DesignStrings.UseContext(contextType));
var loggerFactory = context.GetService<ILoggerFactory>();
loggerFactory.AddProvider(new OperationLoggerProvider(_reporter));
return context;
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
ex = ex.InnerException!;
}
throw new OperationException(
DesignStrings.CannotCreateContextInstance(
contextType ?? contextPair.Key.ShortDisplayName(), ex.Message), ex);
}
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual IEnumerable<Type> GetContextTypes()
=> FindContextTypes().Keys;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing thatView on GitHub (pinned to dbf9771522)
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.
Example fix
// before - context constructor throws at design time (no IConfiguration)
public class AppDbContext : DbContext
{
public AppDbContext(IConfiguration cfg) : base()
=> Connection = cfg.GetConnectionString("Default"); // null at design time
}
// after - add a design-time factory
public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer("Server=.;Database=App;Trusted_Connection=True");
return new AppDbContext(opts.Options);
}
} Defensive patterns
Strategy: try-catch
Try / catch
try { var ctx = ops.CreateContext(contextType); }
catch (OperationException ex) when (ex.Message.Contains("Unable to create a 'DbContext'"))
{
// inspect ex.InnerException for the root cause; add/fix an IDesignTimeDbContextFactory
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- No DbContext was found in assembly '{assembly}'. Ensure that
- No type deriving from DbContext was found. Add [assembly: Db
- The wildcard '*' can only be used with commands that run for
- The exception '{rootException}' was thrown while attempting
- More than one DbContext was found. Specify which one to use.
AI-assisted analysis of dotnet/efcore@dbf9771522 (2026-08-06).
Data as JSON: /api/errors/66cf38312d2db301.
Report an issue: GitHub.