How to enable migrations through code only without using Package manager console

ef-code-first ef-migrations entity-framework entity-framework-6


I am using Entity Framework Code first in my application. But while using this after updating model, every time I have to enable automatic migrations and run update-database using package manager console. Does anyone has solution on this, whether we can automate this and update-database without using package manager console.

11/6/2016 6:22:12 AM

Accepted Answer

You only have to run Enable-Migrations once, to generate the Configuration.cs class and the Initial migration. After that, whenever you change the model you have to generate a new migration by running Add-Migration, and also you have to run Update-Database to apply the migration to your database, but you shouldn't need to run Enable-Migrations again.

If you want to automate the process you can enable the automatic generation of migrations by setting AutomaticMigrationsEnabled = true in the constructor of your Configuration class, and use the MigrateDatabaseToLatestVersion database initializer in your DbContext. This would allow you to just change your model code and not having to do anything with Package Manager Console, no Add-Migration nor Update-Database required. You still need to run Enable-Migrations once, at the beginning, after you create the project, to generate the Initial migration.

Anyway automatic migrations can cause some problems, I wouldn't really recommend you to use them. So I would keep on doing the manual Add-Migration commands whenever your model changes. You can still skip doing the Update-Database if you use the MigrateDatabaseToLatestVersion database initializer.

Another way to do it would be using a DbMigrator to run the equivalent to Update-Database from your code (but you don't need to do this if you are using the MigrateDatabaseToLatestVersion database initializer):

var migrator = new DbMigrator(new DbMigrationsConfiguration());
11/8/2016 9:44:03 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow