Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core apply migrations programmatically

I have test and live db. For test db migrations I use Add-Migration ... and Update-Database syntax in package manager console. But for live db I want to do it programmatically when app is started.

The following code didn't help me:

context.Database.Migrate();

I have error Invalid object name 'TempTenants' when I try to add record to table that doesn't exist. This is my new table.

But I have _EFMigrationsHistory table. And there are all my migrations even those that weren't applied. But I don't see new table.

I will have the same result if I manually remove table from test db and try to reproduce error.

So, context.Database.Migrate(); only create new db with all migrations, if it doesn't exist, but don't update (apply migrations) existing db.

Can I do that? And how can I resolve that?

like image 507
A. Gladkiy Avatar asked Dec 26 '16 12:12

A. Gladkiy


1 Answers

It seems something went wrong. I removed unapplied migrations (records) from __EFMigrationsHistory table (also I needed to revert some table names, primary and foreign keys to previous state) and launched app again.

So, context.Database.Migrate(); apply migrations even for existing databases.

like image 114
A. Gladkiy Avatar answered Sep 28 '22 07:09

A. Gladkiy