Tuesday 22 January 2013

Entity framework delete all entities extension method

Unfortunately when deleting items in entity framework the SQL commands are issued as single DELETE statements for each entity. This really becomes a bottleneck when there are a several thousand items. This handy set of extension methods allows convenient and efficient deletion of all entities for a particular type T. The GetTableName<T> used function even takes into account table mappings set up with the ModelBuilder.

Thanks to Rul Jarimba on StackOverflow for the GetTableName&ltT> function.
public static void DeleteAllEntities<T>(this DbContext db)
    where T : class
    var adapter = (IObjectContextAdapter)db;
    var objectContext = adapter.ObjectContext;
    var sql = string.Format("DELETE FROM {0}", objectContext.GetTableName<T>());
    var entityConnection = objectContext.ExecuteStoreCommand(sql);

public static string GetTableName<T>(this ObjectContext context) 
    where T : class
    string sql = context.CreateObjectSet<T>().ToTraceString();
    Regex regex = new Regex("FROM (?<table>.*) AS");
    Match match = regex.Match(sql);

    string table = match.Groups["table"].Value;
    return table;