Reputation: 4175
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
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
Reputation: 1915
You could use migrations to update the database scheme.
Of course you should not use your custom database initializer.
Upvotes: 1
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