Entity Framework. Delete all rows in table

前端 未结 21 2032
一生所求
一生所求 2020-11-28 01:25

How I can quickly remove all rows in table using Entity Framework?

I am currently using:

var rows = from o in dataDb.Table
           select o;
forea         


        
21条回答
  •  野性不改
    2020-11-28 01:55

    The following works on SQLite database (using Entity Framework)

    It seems that the fastest way to clear all the db tables is using 'context.Database.ExecuteSqlCommand("some SQL")', as some comments above highlighted as well. Here I am going to show how to reset the 'index' count of tables too.

                context.Database.ExecuteSqlCommand("delete from TableA");
                context.Database.ExecuteSqlCommand("delete from sqlite_sequence where name='TableA'");//resets the autoindex
    
                context.Database.ExecuteSqlCommand("delete from TableB");
                context.Database.ExecuteSqlCommand("delete from sqlite_sequence where name='TableB'");//resets the autoindex 
    
                context.Database.ExecuteSqlCommand("delete from TableC");
                context.Database.ExecuteSqlCommand("delete from sqlite_sequence where name='TableC'");//resets the autoindex 
    

    One important point is that if you use foreign keys in your tables, you must first delete the child table before the parent table, so the sequence (hierarchy) of tables during deletion is important, otherwise a SQLite exception may occur.

    Note: var context = new YourContext()

提交回复
热议问题