Monday, May 22, 2023

Unable to generate an explicit migration because the following explicit migrations are pending

There's an old SO question about this, the dreadful Unable to generate an explicit migration because the following explicit migrations are pending.
Not sure if SO answers cover this scenario but this is issue can occur in following setup:
  • you have a parameterless DbContext's constructor and also a connection-string parameter constructor
  • you generate migrations by adding the -ConnectionString and -ConnectionProviderName parameters of add-migration
  • there's no default connection string in the configuration file
The first migration is created correctly but the second one cannot find the migration already applied to the database. Seems it's a bug.
A simple solution is to add a default connection string to the configuration file and drop -ConnectionString and -ConnecitonProviderName from the invocation of add-migration. This picks the default connection string and further checks all new migration against the default database. Still, the other constructor can be used in production code.
public class FooDbContext : DbContext
{
  public FooDbContext() { } // this constructor is used by migration generator
  
  public FooDbContext( string connectionString ) : base( connectionString ) { } // you could be using this from your code
}