Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework 4.3 run migrations at application start

What is the best way to execute all required db migrations at application start with EF 4.3?

like image 928
Sly Avatar asked Feb 14 '12 17:02

Sly


People also ask

How do I run a migration in Entity Framework?

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

What is automatic migration in Entity Framework?

Automatic Migrations allows you to use Code First Migrations without having a code file in your project for each change you make. Not all changes can be applied automatically - for example column renames require the use of a code-based migration.


2 Answers

The best way should be using new MigrateDatabaseToLatestVersion initializer.

Database.SetInitializer<YourContext>(     new MigrateDatabaseToLatestVersion<YourContext, YourMigrationsConfig>()); Database.Initialize(false); 
like image 197
Ladislav Mrnka Avatar answered Oct 04 '22 13:10

Ladislav Mrnka


A great description of the EF 4.3 configuration options can be found at EF 4.3 Configuration File Settings on the ADO.NET team blog. The very last section describes Database Initializers, including the new Code First MigrateDatabaseToLatestVersion initializer.

Although Entity Framework—like so many other features of .NET 4.x—favors convention over configuration, this is one case where it might be very useful to set the MigrateDatabaseToLatestVersion database initializer through your application's config file rather than explicitly code it into your application.

like image 45
Boris Nikolaevich Avatar answered Oct 04 '22 13:10

Boris Nikolaevich