dotnet/efcore · error · OperationException

Unable to create a 'DbContext' of type

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

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.

Solutions

  1. Read the wrapped inner exception message — it states the true cause (e.g. connection string null).
  2. Add an IDesignTimeDbContextFactory<TContext> for the context so design-time construction does not depend on app config.
  3. Ensure any environment variables/secrets the ctor needs are available to the tool process.
  4. Avoid side effects (file/network/config access) in the DbContext constructor or OnConfiguring.

Example fix

// before - context ctor depends on runtime config unavailable at design time
public AppCtx(IConfiguration cfg)
    : base(cfg.GetConnectionString("Db")!) {}

// after - add a design-time factory
public class AppCtxFactory : IDesignTimeDbContextFactory<AppCtx>
{
    public AppCtx CreateDbContext(string[] args)
        => new(new DbContextOptionsBuilder<AppCtx>()
            .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Design;Trusted_Connection=True;")
            .Options);
}
Defensive patterns

Strategy: try-catch

Validate before calling

// validate context can be constructed before running heavy design-time work
using var probe = Activator.CreateInstance(typeof(AppCtx), designOptions) as DbContext;
if (probe is null) throw new InvalidOperationException("Cannot construct AppCtx.");

Try / catch

try { operations.CreateContext(contextType); }
catch (OperationException ex) when (ex.Message.Contains("Unable to create a 'DbContext'"))
{ /* ex.InnerException holds the real cause — fix config/ctor/factory accordingly */ }

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of dotnet/efcore@3a2006ef56 (2026-08-11). Data as JSON: /api/errors/66cf38312d2db301. Report an issue: GitHub.

Appendix: 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 that

View on GitHub (pinned to 3a2006ef56)