Entity Framework. Delete all rows in table

前端 未结 21 2036
一生所求
一生所求 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 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(this DbSet 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 : IRepository where T : class, new()
    {
        private readonly IEfDbContext _context;
    
        public void BulkInsert(IEnumerable entities)
        {
            _context.BulkInsert(entities);
        }
    
        public void Truncate()
        {
            _context.Database.ExecuteSqlCommand($"TRUNCATE TABLE {typeof(T).Name}");
        }
     }
    
     // usage 
     DataAccess.TheRepository.Truncate();
     var toAddBulk = new List();
    
     // 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).

提交回复
热议问题