I want to delete content of all tables (all entities) using Entity Framework 4+. How can this be done?
Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();
RemoveRange(IEnumerable<Object>) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called. RemoveRange(Object[]) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.
Truncating a table is a data layer operation, not an object operation. The equivalent in Entity Framework would be to load all objects from the database and delete them one by one. You don't want that, you want to truncate the table. Then dive down into SQL and truncate that table.
This will perform much, much better than anything involving deleting individual entity objects, assuming the underlying database is MSSQL.
foreach (var tableName in listOfTableNames) { context.ExecuteStoreCommand("TRUNCATE TABLE [" + tableName + "]"); }
Of course, if your tables have foreign-key relationships, you'll need to set up your list of table names in the proper order so that you clear foreign-key tables before you clear any primary-key tables that they might depend upon.
Just for lazy ones, code I came up myself when looking for the answer:
public static void ClearDatabase<T>() where T : DbContext, new() { using (var context = new T()) { var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList(); foreach (var tableName in tableNames) { context.Database.ExecuteSqlCommand(string.Format("DELETE FROM {0}", tableName)); } context.SaveChanges(); } }
Short explanation: I do not truncate tables due to lack of permissions, if it’s not a problem for you, feel free to do so. The table __MigrationHistory is ignored by the where statement.
UPDATE: After some research I came up with better solution (not as nice but deletes only required columns):
public static void ClearDatabase(DbContext context) { var objectContext = ((IObjectContextAdapter)context).ObjectContext; var entities = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace).BaseEntitySets; var method = objectContext.GetType().GetMethods().First(x => x.Name == "CreateObjectSet"); var objectSets = entities.Select(x => method.MakeGenericMethod(Type.GetType(x.ElementType.FullName))).Select(x => x.Invoke(objectContext, null)); var tableNames = objectSets.Select(objectSet => (objectSet.GetType().GetProperty("EntitySet").GetValue(objectSet, null) as EntitySet).Name).ToList(); foreach (var tableName in tableNames) { context.Database.ExecuteSqlCommand(string.Format("DELETE FROM {0}", tableName)); } context.SaveChanges(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With