Enable Automatic Migrations in mvc

asp.net-mvc database-migration ef-migrations entity-framework


I am creating a MVC application where I add new classes very often. As the classes are related to each other and the test data in the the tables already created are of no interest I prefer to go with AutomaticMigrations.

i use the following command to set the database to the initial state.

Update-Database –TargetMigration: $InitialDatabase

But the problem is that it doesn't work always. What could be the possible reasons that it goes wrong? I am not familiar with Code First Migrations.

The error is mostly thrown during the runtime stating the DbContext was changed. I make sure there are no dependencies in the existing tables with the dropped tables before enabling the Migrations. I also get an error that states

Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong.

I am looking for general help on the topic.

9/29/2015 7:46:41 AM

Accepted Answer

For automatic migrations first you should set Database Initializer in your Database Context constructor.

public class YourDBContext: DbContext 
    public YourDBContext(): base("ConnectionString") 
         Database.SetInitializer<YourDBContext>(new CreateDatabaseIfNotExists<YourDBContext>());

You can also create custom Database initializer implementing CreateDatabaseIfNotExists<YourDBContext> with overridden seed method to provide initial data.

Second you should enable automatic migrations using command in Package Manager Console Enable-Migrations -EnableAutomaticMigrations

Then using Update-Database command in Package Manager Console will apply to database all the pending changes that you have made after last migration.

Update : Use Verbose with update database command to see what script is generated

Update-Database –Verbose
9/29/2015 1:29:20 PM

Popular Answer

You should use DropCreateDatabaseIfModelChanges if you always want to recreate the db rather than targeting the initialdatabase migration. More on the topic on the asp.net website In your context's constructor, e.g

public class SchoolDBContext: DbContext 
        public SchoolDBContext(): base("SchoolDBConnectionString") 
         Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow