Entity Framework. Delete all rows in table

前端 未结 21 1775
一生所求
一生所求 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()

    0 讨论(0)
  • 2020-11-28 01:56

    This works Properly in EF 5:

    YourEntityModel myEntities = new YourEntityModel();
    
    var objCtx = ((IObjectContextAdapter)myEntities).ObjectContext;
    objCtx.ExecuteStoreCommand("TRUNCATE TABLE [TableName]");
    
    0 讨论(0)
  • 2020-11-28 01:58

    Delete all records. Do not reset the primary index like "truncate".

    /// <summary>
    /// SET - DELETE all record by table - no truncate - return deleted records
    /// </summary>
    public static int setListDelAllMYTABLE()
    {
        // INIT
        int retObj = 0;
        using (MYDBEntities ctx = new MYDBEntities())
        {
            // GET - all record
            var tempAllRecord = ctx.MYTABLE.ToList();
            // RESET
            ctx.MYTABLE.RemoveRange(tempAllRecord);
            // SET - final save
            retObj += ctx.SaveChanges();
        }
        // RET
        return retObj;
    }
    
    0 讨论(0)
  • 2020-11-28 01:58

    In my code I didn't really have nice access to the Database object, so you can do it on the DbSet where you also is allowed to use any kind of sql. It will sort of end out like this:

    var p = await _db.Persons.FromSql("truncate table Persons;select top 0 * from Persons").ToListAsync();
    
    0 讨论(0)
  • 2020-11-28 02:00

    If MVC, you can do:

    public async Task<IActionResult> DeleteAll()
    {
        var list = await _context.YourClass.ToListAsync();
        _context.YourClass.RemoveRange(list);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    
    0 讨论(0)
  • 2020-11-28 02:01

    I came across this question when I had to deal with a particular case: fully updating of content in a "leaf" table (no FKs pointing to it). This involved removing all rows and putting new rows information and it should be done transactionally (I do not want to end up with an empty table, if inserts fails for whatever reason).

    I have tried the public static void Clear<T>(this DbSet<T> dbSet) approach, but new rows are not inserted. Another disadvante is that the whole process is slow, as rows are deleted one by one.

    So, I have switched to TRUNCATE approach, since it is much faster and it is also ROLLBACKable. It also resets the identity.

    Example using repository pattern:

    public class Repository<T> : IRepository<T> where T : class, new()
    {
        private readonly IEfDbContext _context;
    
        public void BulkInsert(IEnumerable<T> entities)
        {
            _context.BulkInsert(entities);
        }
    
        public void Truncate()
        {
            _context.Database.ExecuteSqlCommand($"TRUNCATE TABLE {typeof(T).Name}");
        }
     }
    
     // usage 
     DataAccess.TheRepository.Truncate();
     var toAddBulk = new List<EnvironmentXImportingSystem>();
    
     // fill toAddBulk from source system
     // ...
    
     DataAccess.TheRepository.BulkInsert(toAddBulk);
     DataAccess.SaveChanges();
    

    Of course, as already mentioned, this solution cannot be used by tables referenced by foreign keys (TRUNCATE fails).

    0 讨论(0)
提交回复
热议问题