Database.Migrate() creating database but not tables, EF & .NET Core 2
Another classic case of struggling with something for a day or two only to find the answer half an hour after posting a question here. Posting my solution incase other people have had a similar issue.
TLDR - _dbContext.Database.Migrate();
doesn't create migrations.
Basically, dbContext.Database.EnsureCreated()
doesn't care about migrations, which is why it generated the full database inc tables (however then of course you can't migrate).
_dbContext.Database.Migrate();
applies the migrations and creates the database if it doesn't exist however it doesn't create the tables if there's no migration.
Basically I have a project as a resource, I was trying to duplicate the project from a new application generated by the user but as I'd never run any migrations in the resource project there was nothing to migrate. Running the Add-Migration Initial
in the PMC in the resource project gave the project it's initial migration files so then when I ran migrate on a new database it knew which tables to create.
In my case I had multiple projects and DesignTimeDbContextFactory
was pointing to a
MigrationsAssembly
but in startup sqlOptions
were not.
so when DI creates DbContext
it does't know there are pending migrations.
you can check you pending migrations with
dbContext.Database.GetPendingMigrations();
before Migrate();
to check if it has found migrations or not
Solution is add migration MigrationsAssembly
in sqlOptions
services.AddDbContext<BM_OCR_DbContext>(options =>
{
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
sqlServer => sqlServer.MigrationsAssembly("BM.OCR.Server"));
});