user3698892
user3698892

Reputation: 13

Database migration using code first in mvc 4

I have created my mvc 4 application using code first and accordingly database and table also generated now i want to delete one column (from backend) of my table. so i just want to know is there any way so that changes can occur in my code automatically according to change in database.

Upvotes: 1

Views: 261

Answers (2)

chandresh patel
chandresh patel

Reputation: 309

Well if you are using code first technique then remove column from your model and run migration script(google it) this will remove column from your database. But what you want is reverse which I am not sure could be done or not.

Upvotes: 0

aamir sajjad
aamir sajjad

Reputation: 3039

through package manager console using migration technique

PM> enable-migrations -EnableAutomaticMigrations

in code configuration do the following

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

now when model changes do the following.

PM> update-database

Doing it through code

Use DropCreateDatabaseAlways initializer for your database. It will always recreate database during first usage of context in app domain:

Database.SetInitializer(new DropCreateDatabaseAlways<YourContextName>());

Actually if you want to seed your database, then create your own initializer, which will be inherited from DropCreateDatabaseAlways:

public class MyInitializer : DropCreateDatabaseAlways<YourContextName>
{
     protected override void Seed(MagnateContext context)
     {
         // seed database here
     }
}

And set it before first usage of context

Database.SetInitializer(new MyInitializer());

Upvotes: 1

Related Questions