Delete all entities in Entity Framework

后端 未结 8 1665
天命终不由人
天命终不由人 2020-12-13 17:10

I want to delete content of all tables (all entities) using Entity Framework 4+. How can this be done?

8条回答
  •  囚心锁ツ
    2020-12-13 17:34

    truncate could not delete within foreign key.

    then I made extension method for DbContext.

    usage is simple.

    db.Truncates(); // all table deletes.

    db.Truncates("Test1", "Test2"); // only "Test1, Test2" table delete

    public static class DbContextExtension
    {
        public static int Truncates(this DbContext db, params string[] tables)
        {
            List target = new List();
            int result = 0;
    
            if (tables == null || tables.Length == 0)
            {
                target = db.GetTableList();
            }
            else
            {
                target.AddRange(tables);
            }
    
            using (TransactionScope scope = new TransactionScope())
            {
                foreach (var table in target)
                {
                    result += db.Database.ExecuteSqlCommand(string.Format("DELETE FROM  [{0}]", table));
                    db.Database.ExecuteSqlCommand(string.Format("DBCC CHECKIDENT ([{0}], RESEED, 0)", table));
                }
                
                scope.Complete();
            }
    
            return result;
        }
    
        public static List GetTableList(this DbContext db)
        {
            var type = db.GetType();
    
            return db.GetType().GetProperties()
                .Where(x => x.PropertyType.Name == "DbSet`1")
                .Select(x => x.Name).ToList();
        }
    }
    

提交回复
热议问题