Created
April 10, 2019 18:13
-
-
Save lcssanches/32682d0d5ebb858aa64acef62a209741 to your computer and use it in GitHub Desktop.
Entity Framework Core: Clear all tables
This file contains hidden or 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
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