dotnet ef "Unable to create a DbContext" in CI
This means EF tools could not instantiate your DbContext at design time. It needs either a parameterless constructor, DI registration the tools can resolve, or an IDesignTimeDbContextFactory. In CI it often fails because a connection string or environment variable present locally is absent.
What this error means
The EF command fails with "Unable to create an object of type DbContext" plus a hint about adding a design-time factory. It reproduces every run for the same configuration.
Unable to create an object of type 'AppDbContext'. For the different patterns supported
at design time, see https://go.microsoft.com/fwlink/?linkid=851728Common causes
Design-time configuration is missing
The DbContext relies on DI/config (e.g. a connection string from configuration) that is not available at design time in CI, so the tools cannot construct it.
No design-time factory and no usable constructor
The context has no parameterless constructor and no IDesignTimeDbContextFactory, so EF cannot create it without running the app.
How to fix it
Add a design-time factory
- Implement
IDesignTimeDbContextFactory<AppDbContext>that builds options from a CI-available connection string. - Supply the connection string via a CI env var or a non-secret design-time default.
- Re-run the EF command.
public sealed class DesignFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var cs = Environment.GetEnvironmentVariable("EF_CONN") ?? "Host=localhost;Database=app";
var opts = new DbContextOptionsBuilder<AppDbContext>().UseNpgsql(cs).Options;
return new AppDbContext(opts);
}
}How to prevent it
- Provide a design-time factory so EF tooling never depends on app startup.
- Set a CI env var for the design-time connection string.