Skip to content

Instantly share code, notes, and snippets.

@rodrigoramirez93
Last active May 9, 2020 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigoramirez93/2fa2d288a870de83e4574994c433bd8c to your computer and use it in GitHub Desktop.
Save rodrigoramirez93/2fa2d288a870de83e4574994c433bd8c to your computer and use it in GitHub Desktop.
Delete all data from every table in database except table "__EFMigrationsHistory"
//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