Entity Framework. Delete all rows in table

前端 未结 21 1770
一生所求
一生所求 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:47

    This works for me... EF v3.1.5

    context.ModelName.RemoveRange(context.ModelName.ToList());
    context.SaveChanges();
    
    0 讨论(0)
  • 2020-11-28 01:49

    If you wish to clear your entire database.

    Because of the foreign-key constraints it matters which sequence the tables are truncated. This is a way to bruteforce this sequence.

        public static void ClearDatabase<T>() where T : DbContext, new()
        {
            using (var context = new T())
            {
                var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList();
                foreach (var tableName in tableNames)
                {
                    foreach (var t in tableNames)
                    {
                        try
                        {
    
                            if (context.Database.ExecuteSqlCommand(string.Format("TRUNCATE TABLE [{0}]", tableName)) == 1)
                                break;
    
                        }
                        catch (Exception ex)
                        {
    
                        }
                    }
                }
    
                context.SaveChanges();
            }
        }
    

    usage:

    ClearDatabase<ApplicationDbContext>();
    

    remember to reinstantiate your DbContext after this.

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

    In EFCore (version i am using is 3.1) you can use the following to remove all rows -

    context.Database.ExecuteSqlRaw("TRUNCATE TABLE [TableName]");
    
    0 讨论(0)
  • 2020-11-28 01:53

    For those that are googling this and ended up here like me, this is how you currently do it in EF5 and EF6:

    context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
    

    Assuming context is a System.Data.Entity.DbContext

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

    You can do that without Foreach

    dataDB.Table.RemoveRange(dataDB.Table);
    dataDB.SaveChanges();
    

    This will remove all rows

    0 讨论(0)
  • 2020-11-28 01:54
    var list = db.Discounts.ToList().Select(x => x as Discount);
    foreach (var item in list)
    {
        db.Discounts.Remove(item);
    }
    db.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题