Entity Framework. Delete all rows in table

前端 未结 21 1771
一生所求
一生所求 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:10
    using (var context = new DataDb())
    {
         var ctx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext;
         ctx.ExecuteStoreCommand("DELETE FROM [TableName] WHERE Name= {0}", Name);
    }
    

    or

    using (var context = new DataDb())
    {
         context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
    }
    
    0 讨论(0)
  • 2020-11-28 02:10

    if

          using(var db = new MyDbContext())
                {
                   await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
                }
    

    causes

    Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.

    I use this :

          using(var db = new MyDbContext())
                   {
                       await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
                   }
    
    0 讨论(0)
  • 2020-11-28 02:14

    Warning: The following is only suitable for small tables (think < 1000 rows)

    Here is a solution that uses entity framework (not SQL) to delete the rows, so it is not SQL Engine(R/DBM) specific.

    This assumes that you're doing this for testing or some similar situation. Either

    • The amount of data is small or
    • The performance doesn't matter

    Simply call:

    VotingContext.Votes.RemoveRange(VotingContext.Votes);
    

    Assuming this context:

    public class VotingContext : DbContext
    {
        public DbSet<Vote> Votes{get;set;}
        public DbSet<Poll> Polls{get;set;}
        public DbSet<Voter> Voters{get;set;}
        public DbSet<Candidacy> Candidates{get;set;}
    }
    

    For tidier code you can declare the following extension method:

    public static class EntityExtensions
    {
        public static void Clear<T>(this DbSet<T> dbSet) where T : class
        {
            dbSet.RemoveRange(dbSet);
        }
    }
    

    Then the above becomes:

    VotingContext.Votes.Clear();
    VotingContext.Voters.Clear();
    VotingContext.Candidacy.Clear();
    VotingContext.Polls.Clear();
    await VotingTestContext.SaveChangesAsync();
    

    I recently used this approach to clean up my test database for each testcase run (it´s obviously faster than recreating the DB from scratch each time, though I didn´t check the form of the delete commands that were generated).


    Why can it be slow?

    1. EF will get ALL the rows (VotingContext.Votes)
    2. and then will use their IDs (not sure exactly how, doesn't matter), to delete them.

    So if you're working with serious amount of data you'll kill the SQL server process (it will consume all the memory) and same thing for the IIS process since EF will cache all the data same way as SQL server. Don't use this one if your table contains serious amount of data.

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