Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete all data in the Seed method?

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?

like image 510
André Pena Avatar asked Dec 19 '22 11:12

André Pena


1 Answers

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
}
like image 115
André Pena Avatar answered Mar 11 '23 08:03

André Pena