-
Notifications
You must be signed in to change notification settings - Fork 57
EnsureClean your database
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 |
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.
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)