EF (Entity Framework) Migrations are a way to generate versioned Database Scripts from c# Classes. Developpers can specify which Changes are sumerized to a new Version.
EF Migrations are enabled by Package Manager Console Command
Enable-Migrations. It creates a Migration Folder and a Configuration Class in your Visual Studio Project.
When all changes for a new Version are made to the Entity c# Classes, the Package Manager Console Command
"Add Migration (Migrationname)" creates a c# Class deriving from DbMigrations with a Up and a Down Method, which executes the necesarry SQL for Up/Downgrading the DB. The DB itself is upgraded either by the Package Manager Console Command
Update-Database (which also lets you create script by -script Parameter) or by using Database Initializer, which are executed when the DBContext first Needs the Database:
//upgrades Production Datebase, maybe first make a backup
Database.SetInitializer(new MigrateDatabaseToLatestVersion
());
//creates new Db
Database.SetInitializer(new CreateDatabaseIfNotExists
());
So the Software itself can automatically create or upgrade the needed Database.
Summary of Commands and Options:
https://coding.abel.nu/2012/03/ef-migrations-command-reference/ or in the Package Manager Console: get-help Add-Migration
most important Package Manager Console Commands:
- Enable-Migrations
- Add Migration (Migrationname)
- Update-Database
Examples:
getting all migrations which have been deployed to a database so far:
get-migrations
adding a migration after changing EF-Relevant Code:
add-migration Mig0025
update Database to a specific Migration
Update-Database -TargetMigration Mig0005 -Verbose -connectionStringName Db1
Add Custom SQL to Migration
use the SQL Methode in the Up / Down Methode: