Skip to content

Instantly share code, notes, and snippets.

@lcssanches
Created April 10, 2019 18:13
Show Gist options
  • Save lcssanches/32682d0d5ebb858aa64acef62a209741 to your computer and use it in GitHub Desktop.
Save lcssanches/32682d0d5ebb858aa64acef62a209741 to your computer and use it in GitHub Desktop.
Entity Framework Core: Clear all tables
public static class ExtensionContextClear {
public static void Clear(this DbContext context) {
var properties = context.GetType().GetProperties();
foreach(var property in properties) {
var setType = property.PropertyType;
bool isDbSet = setType.IsGenericType && (typeof(DbSet < > ).IsAssignableFrom(setType.GetGenericTypeDefinition()));
if (!isDbSet) continue;
var dbSet = (dynamic) property.GetValue(context, null);
dbSet.RemoveRange(dbSet);
}
context.SaveChanges();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment