I'm using Entity Framework code first with migrations and I want to delete all data in the Seed method, from all tables, except from the __MigrationHistory table. Right after my database is clean, I'll proceed with the seed method, but just adding new objects.
I want this because I develop using a development database and I constantly want to reset it to a default state.
So, what's the best way to delete all data, from all tables, except for __MigrationHistory, in the seed method?
public override void Seed(YourNamespace.Model.DbContext context)
{
// Deletes all data, from all tables, except for __MigrationHistory
context.Database.ExecuteSqlCommand("sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'");
context.Database.ExecuteSqlCommand("sp_MSForEachTable 'IF OBJECT_ID(''?'') NOT IN (ISNULL(OBJECT_ID(''[dbo].[__MigrationHistory]''),0)) DELETE FROM ?'");
context.Database.ExecuteSqlCommand("EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'");
// proceed with the seed here
}
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