Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP - Core Migrate EF Core SQL DB on Startup

Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to do it programatically.

like image 349
Zeus82 Avatar asked Jun 12 '16 23:06

Zeus82


People also ask

How do I turn on automatic migration in Entity Framework?

Open the Package Manager Console from Tools → Library Package Manager → Package Manager Console and then run the enable-migrations –EnableAutomaticMigration:$true command (make sure that the default project is the project where your context class is).


2 Answers

A note from documentation on the call to db.Database.EnsureCreated():

Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

You may just want to call db.Database.Migrate().

Comment taken from source found above declaration here.

like image 89
steamrolla Avatar answered Oct 21 '22 16:10

steamrolla


You can use

db.Database.EnsureCreated(); 

to get your db up to date with your current model. If you want to enable migrations (If subsequent migrations are suspected), then use

db.Database.Migrate(); 

and put your subsequent migrations over time.

like image 44
Janshair Khan Avatar answered Oct 21 '22 16:10

Janshair Khan