EF6 Code First drop tables (not entire database) when model changes

c# ef-migrations entity-framework

Question

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?

1
5
6/13/2014 3:41:27 PM

Accepted Answer

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
}
3
5/23/2017 12:16:38 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow