2

I want to delete content (only data, but not the structure and foreign keys.) of all tables (all entities using Entity Framework 4+). How can this be done? I am using SQLCE and Entity framework with Visual Studio 2010.

entities.ExecuteStoreCommand("DELETE FROM TABLENAME");

Above query doesn't delete all rows. Later, I would also be using a where claused like

entities.ExecuteStoreCommand("DELETE FROM TABLENAME WHERE COL1=0");
user2330678
  • 2,221
  • 14
  • 43
  • 67

2 Answers2

0

In SQL you can use TRUNCATE TABLENAME but if you have foreign keys, you will have to set the key count to 0, then truncate, then set keycount to 1 again:

"SET FOREIGN_KEY_CHECKS = 0;"
"TRUNCATE TABLE TALBENAME;"
"SET FOREIGN_KEY_CHECKS = 1;"

OR

"ALTER TABLE TABLENAME;"
"DROP CONSTRAINT FK_Name;"
Ben
  • 2,433
  • 5
  • 39
  • 69
0

You can use the EntityFramework.Extended library to perform bulk deletes. Here's a sample of what it looks like:

//delete all users where FirstName matches
context.Users.Delete(u => u.FirstName == "firstname");

since you want to delete everything, you could use it like this:

//delete all users
context.Users.Delete(u => u.UserId >= 0);

you can download the package from nuget, or their Github: https://github.com/loresoft/EntityFramework.Extended

It occurred to me that you may be having problems with delete because you need to enable cascade on delete. If you are using the code-first method of EF, you can do it like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true); // <-- add this to the code-first model builder.
}
solidau
  • 4,021
  • 3
  • 24
  • 45
  • Can you give me a link for download from Nuget? – user2330678 Mar 14 '14 at 01:05
  • 1
    it is a little more complicated than that. Nuget is a package management solution for .NET. you dont really download the file, at least not directly. instead, you install the package into your project. here's a brief overview of how you can use the PackageManager Console: http://docs.nuget.org/docs/start-here/using-the-package-manager-console – solidau Mar 14 '14 at 01:07
  • Will it work with SQL compact? Please excuse my ignorance. I am new to sqlce. – user2330678 Mar 14 '14 at 01:09
  • as far as i know, yes – solidau Mar 14 '14 at 01:10