I use Entity Framework code first and set AutomaticMigrationsEnabled true by this code :
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, MigrateDBConfiguration>());
//////////////////////////////////
public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
public MigrateDBConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
In first run the project it work fine and create database and tables. after I change model and drop some field or add new fields and run Add-Migration, Migration class generated but after run project this exception occur :
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The model backing the 'DBContext' context has changed since the database was created.
EDIT: Like answer of arturo menchaca I change may code like this :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DBContext, MigrateDBConfiguration<DBContext>>());
...
But ths exception is ocure :
There is already an object named 'MyTable' in the database.
I want apply my migration.
Finally I found a solution to my problem. I call this method in each application start :
If you have change in your entities, you need first run
add-migration
to create the migration script.After that in your
Global.asax
you need to have some code like this
every time that you run your asp.net project it'll check if you have a new migration to run and run
update-database
automatically for you.Automatic Migrations means that you don't need to run
add-migration
command for your changes in the models, but you have to runupdate-database
command manually.If Automatic Migrations is enabled when you call
update-database
, if there are pending changes in your models, an 'automatic' migration will be added and database will be updated.If you want that your database is updated without need to call
update-database
command, you can addDatabase.SetInitializer(...)
inOnModelCreating()
method on your context, like so:Note that you should declare
DbMigrationsConfiguration
andMigrateDatabaseToLatestVersion
with your real context, not the defaultDbContext
.