Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

How to drop and create only tables which are changed in Code First - Entity Framework

I am using Code First approach in Entity Framework.

I have created a custom database initializer as below.

public class CustomInit : IDatabaseInitializer<APIContext>
    {
        public void InitializeDatabase(APIContext context)
        {
            bool dbExists;

            dbExists = context.Database.Exists();

            if (dbExists)
            {
                // remove all tables
                context.Database.ExecuteSqlCommand(
                   "EXEC sp_MSforeachtable @command1 = \"DROP TABLE ?\"");

                // create all tables
                var dbCreationScript = ((IObjectContextAdapter)
                       context).ObjectContext.CreateDatabaseScript();
                context.Database.ExecuteSqlCommand(dbCreationScript);

                context.SaveChanges();
            }
            else
            {
                throw new ApplicationException("No database is present");
            }
        }
    }

As per the above code, all tables in database is dropped and recreated.

What I need to do is to drop and create tables/entity which are changed in Code like - adding or removing any column etc.

Is there anyway we can do this?

Any guidance is much appreciated.

Upvotes: 1

Views: 2054

Answers (3)

Madhu
Madhu

Reputation: 439

You can revert back to initial migration which you have applied by updating the database.

Update-database -targetMigration "MigrationName"

Above command reverts all the db changes whatever you have applied as part of EF migrations.

Upvotes: 0

Ivan R.
Ivan R.

Reputation: 1915

You could use migrations to update the database scheme.

  1. Open Package Manager Console (Tools -> Library Package Manager -> Package Manager Console)
  2. Run Enable-Migration command
  3. Change your model
  4. Run Add-Migration command in Package Manager Console.
  5. Run Update-Database command to apply your model changes to the database.

Of course you should not use your custom database initializer.

Upvotes: 1

steliosbl
steliosbl

Reputation: 8921

The simplest solution is to add this initialization to your in your context's constructor:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());

This will check your model against the database every time you run your program, and automatically drop and re-create the database if the model has been modified.

If you don't want to drop the database, and simply update it, then you can use the following initialization:

Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, Config>());

Be advised however, neither of these work in Entity Framework Core, as Microsoft haven't and don't intend to implement automatic migrations for the .Net Core version.

Upvotes: 0

Related Questions