Last active
May 9, 2020 19:16
-
-
Save rodrigoramirez93/2fa2d288a870de83e4574994c433bd8c to your computer and use it in GitHub Desktop.
Delete all data from every table in database except table "__EFMigrationsHistory"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//this methods aims to be used on a testing database. It's extremely harmful, proceed with caution | |
public static class DatabaseContextHelper | |
{ | |
public static readonly string DisableTablesConstraintsCommand = "EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' "; | |
public static readonly string DeleteAllTablesDataExceptMigrationsTableCommand = "EXEC sp_MSforeachtable 'if (\"?\" NOT IN (\"[dbo].[__EFMigrationsHistory]\")) DELETE FROM ?'"; | |
public static readonly string EnableTablesConstraintsCommand = "EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'"; | |
public static void DeleteAllDataExceptMigrations(this DbContext context) | |
{ | |
context.Database.ExecuteSqlCommand(ContextExtension.DisableTablesConstraintsCommand); | |
context.Database.ExecuteSqlCommand(ContextExtension.DeleteAllTablesDataExceptMigrationsTableCommand); | |
context.Database.ExecuteSqlCommand(ContextExtension.EnableTablesConstraintsCommand); | |
} | |
} | |
//usage: | |
context.DeleteAllDataExceptMigrations(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment