Search code examples
c#dbset

Why is RemoveRange not clearing DbSet?


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.


Solution

  • This is happening because of deferred execution. Try:

     dbSet.RemoveRange(dbSet.ToList());