Share via


How to Delete All Objects From an Entity in the Entity Framework 4

In a previous blog entry, I described how happy I was with Code-First Development with Entity Framework 4.  It was a good first impression, and then I had to go beyond my initial spike and create a set of integration tests that would actually work over and over.  So I wanted to delete all of the rows from one of my tables, but I couldn’t figure out how.  Linq doesn’t appear to be that great at mass deletions, and EF doesn’t appear to have any intrinsic functionality for this.  All I wanted to do was:

DELETE FROM foo;

I could have dropped and recreated the database on the fly, and I may end up doing that in the future sometime, but at the moment that seems a little extreme.  It looks like the following gets the job done, but you have to “drop down” to the SQL level to accomplish it:


         public void DeleteAll()
        {
            var snap = new SnapIDs();
            var cmd = snap.Database.Connection.CreateCommand();
            cmd.CommandText = "DELETE FROM ServerConfigurationModels";
            snap.Database.Connection.Open();
 
            cmd.ExecuteNonQuery();
 
            snap.Database.Connection.Close();
        }

Not the ideal solution – I’d rather do something like clear my DbSet and SaveChanges() – but it’s pretty SQL agnostic at least.

Comments

  • Anonymous
    July 26, 2010
    You've been kicked (a good thing) - Trackback from DotNetKicks.com