Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all entities in Entity Framework

I want to delete content of all tables (all entities) using Entity Framework 4+. How can this be done?

like image 855
Cartesius00 Avatar asked May 22 '11 16:05

Cartesius00


People also ask

How delete all data from table in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

What is RemoveRange in Entity Framework?

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.

How do I truncate a table in EF core?

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.


2 Answers

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.

like image 114
Joel Mueller Avatar answered Oct 10 '22 14:10

Joel Mueller


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(); } 
like image 45
Wojciech Markowski Avatar answered Oct 10 '22 12:10

Wojciech Markowski