Do you just want to automatically update the database to the latest version when and where ever your application runs (development and production)?
This may not be a good idea, except in very simple scenarios where you know you can trust automatic migration and manually migrating the database(s) is not feasible. Please see this answer: https://stackoverflow.com/a/15718190/2279059 . If you disregard this warning, read on.
Add the following to web.config
:
<entityFramework>
<contexts>
<context type="MyAssembly.MyContext, MyAssembly" disableDatabaseInitialization="false">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyAssembly.MyContext, MyAssembly], [MyAssembly.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
This may look scary, but it does basically the same as the following code:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration>());
If you have no luck with web.config
, then you may also try to put this code into Global.asax
. I personally prefer configuration over code.
If you want your config file to look cleaner, you can also derive a new class from the template MigrateDatabaseToLatestVersion
class so you don't need to use the cryptic syntax for passing type arguments in your web.cofig
file:
public class MyDatabaseInitializer : public MigrateDatabaseToLatestVersion<MyContext, Migrations.Configuration> {}
What this does is to set a database initializer which automatically updates the database to the latest version.
(Source and more details: Entity Framework Code First Web.config Initialization)