Remove all Entity Framework entities.

.net c# entity-framework wpf

Question

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

1
56
5/12/2017 11:30:23 AM

Accepted Answer

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.

48
5/22/2011 6:03:25 PM

Popular Answer

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();
    }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow