Tuesday, 24 December 2013

Enabling Automatic Code First Migration

This post is describing how to set automatic Entity Framework Code Fist migration, for the manual migration please see my previous post.

Automatic Code First migration feature is useful during development phase when database has not gone into production environment yet.

If you haven't got an EF migration Configuration.cs file then you can run this command on Package Manager Console:
Enable-Migrations –EnableAutomaticMigrations
This will add a folder called 'Migrations' in the project and a file called Configuration.cs with this setting in the constructor method:
AutomaticMigrationsEnabled = true;

If you have already got the file, make sure that AutomaticMigrationsEnabled property setting is set to true in the constructor.

Secondly, ensure that MigrateDatabaseToLatestVersion initialisation option is set on the project startup file (for example; inside global.asax)
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
DatabaseContext: your database context class name
Configuration: this is the Configuration file discussed earlier. You would need to make the class to be public if you put the initialiser inside other project.

Also if we want the automatic migration to allow data loss (for example; allowing column to be removed) then AutomaticMigrationDataLossAllowed property would need to be set to true.

So the constructor will have these settings:
public Configuration()
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;

No comments: