1

I have the following extension method for clearing DbSet<T>:

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

And the usage looks like this:

databaseContext.Users.Clear();
databaseContext.SaveChanges();

Now the question: why is the code not working, why is the table Users not empty?

EDIT

The correct answer is that SaveChanges throws an exception because of mutual entity relations and so some entities are not removed. I failed to notice the exception because it ran as a cleanup of a [integration] MSTest suite with all tests passing. But still, my original implementation did contain another mistake so I'm marking one of the responses pointing it out as the response.

DomJourneyman
  • 65
  • 2
  • 9

2 Answers2

3

This is happening because of deferred execution. Try:

 dbSet.RemoveRange(dbSet.ToList());
Yuli Bonner
  • 1,189
  • 8
  • 12
2

In the context you are executing RemoveRange, there is no any rows retrieved from database. By adding ToList() before RemoveRange dbSet.RemoveRange(dbSet.ToList()), result is better. Please remember, that RemoveRange does delete one-by-one..

..where we come to performance. If you want to clear big amounts of data with good performance:

  • Truncate table with SqlCommand (whole table) or
  • Use bulk operations from external library
Risto M
  • 2,919
  • 1
  • 14
  • 27
  • Looks there's something fishy - I'm running this as clean-up code for my MSTest class, I clear all the ```DbSet```s one by one and then ```SaveChanges```, but if I add one extra SaveChanges into this sequence, everything up to this first extra save command is cleared. – DomJourneyman Feb 05 '18 at 21:19