I'm doing Code First development with Entity Framework 6, using Database Migrations, and I'm using a new database that is populated with sample seed data. I'd like to be able to initialize my database with that seed data any time I change the model.
The catch is this: I don't have database create permissions; because of this, I can't just utilize DropCreateDatabaseIfModelChanges.
Is there a way that I can programmatically drop all of my tables, or am I stuck manually deleting them from the database each time?
Ultimately, I didn't need to delete the tables, just the data they contained.
I ended up solving this by simply truncating a list of tables at the beginning of my Seed method, based on this answer.
protected override void Seed(MyContext context)
{
var listOfTables = new List<string> { "Table1", "Table2", "Table3" };
foreach (var tableName in listOfTables)
{
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [" + tableName + "]");
}
context.SaveChanges();
// seed data below
}
If you're not using automatic migrations, but code based migrations, you can back all the way down to the first version using the follow command:
Update-Database –TargetMigration: 0
This will follow the Down path on all of your migrations until you have a clean database. Then you can execute:
Update-Database
This will bring everything back up to date. This solution assumes you've properly maintained your Down path and seeded your data with Migrations. I do this for my integration tests to ensure I start with the data in an expected state.