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?
To remove a table, simply remove the corresponding DbSet<MyClass> and any references to that class in other parts of your model and EF will add a DropTable to the migration automatically. If you are no longer using the class for non-Entity Framework purposes you can delete it.
To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.
Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.
In code first approach we will first create entity classes with properties defined in it. Entity framework will create the database and tables based on the entity classes defined. So database is generated from the code. When the dot net code is run database will get created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With