Remove all Entity Framework entities.

.net c# entity-framework wpf

Question

Using Entity Framework 4+, I want to remove all of the content from all tables (all entities). How is this accomplished?

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

Accepted Answer

If the underlying database is MSSQL, then this will work much, much, much better than anything requiring the deletion of individual entity objects.

foreach (var tableName in listOfTableNames)
{
    context.ExecuteStoreCommand("TRUNCATE TABLE [" + tableName + "]");
}

Naturally, if your tables include foreign-key connections, you must arrange your list of table names such that foreign-key tables are cleared before any primary-key tables on which they may rely.

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

Popular Answer

Just for the lazy, here's some code I created on my own while seeking for the solution:

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

Brief explanation: Because I lack the necessary rights, I do not truncate tables. If this is not a concern for you, feel free to do so. The where clause ignores the table __MigrationHistory.

UPDATE: After some investigation, I developed a better method (which is less appealing but just deletes necessary 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