Skip to content

EnsureClean your database

Jon P Smith edited this page Jan 26, 2022 · 4 revisions

The EfCore.TestSupport library has a extension method called EnsureClean which is fast way of resetting a test database's schema to match the current EF Core's Model of the database, and also leaves the database with not data (rows) in it. Its effectively a quicker version of calling EnsureDeleted / EnsureCreated.

The EnsureClean works with SQL Server, and the code came from the EF Core code (with their permission). The PostgreSQL version came from a [stack overflow answer](see https://stackoverflow.com/a/13823560/1434764) and some help from Shay Rojansky (github @roji) on the EF Core team.

You use this method in the same way as a EnsureCreated, e.g.

[Fact]
public void TestSqlServerEnsureClean()
{
    //SETUP

    //ATTEMPT
    var options = this.CreateUniqueClassOptions<EfCoreContext>();
    using var context = new EfCoreContext(options)
    context.Database.EnsureClean();

    //... left of test left out
}

The (rough) time differences between the EnsureDeleted / EnsureCreated approach and the EnsureClean approach are shown below.

Database Approach Timing (ms)
SQL Server EnsureDeleted / EnsureCreated ~1,500
EnsureClean (thanks to EF Core team) ~750
PostgreSQL EnsureDeleted / EnsureCreated 320
EnsureClean (thanks to Shay Rojansky) 70

Using EnsureClean when using migrations

Sometimes its useful to create database using a migration, and the EnsureClean can help. If you call method with a false parameter i.e. context.Database.EnsureClean(false), then it will wipe the database schema but not recreate the new database. This allows you to execute a migration after the EnsureClean(false) and the database will be migrated.

NOTE: There is a limitation in the SQL Server EnsureClean, in that it doesn't delete the default migration table, so your migration must use a different migration table name.

Clone this wiki locally