EnsureCreated prepares an EF Core database by creating its database and schema when needed, without applying migrations. section 36.4
For SQLite in-memory tests, EnsureCreated provides a simple setup path:
- Configure a SqliteConnection with the DataSource=:memory: connection string. section 36.4
- Open the connection, configure UseSqlite(), create the DbContext, and call context.Database.EnsureCreated(). section 36.5
- Keep the connection open while tests use the database; closing it destroys the SQLite in-memory database. section 36.5
- Prefer it here because migrations made for SQL Server or PostgreSQL cannot be run directly against SQLite. section 36.4
Preparing an isolated test database
A test opens a SQLite in-memory connection, configures AppDbContext with UseSqlite(connection), calls EnsureCreated(), and then adds test recipes. Each newly created database can be populated and torn down independently. section 36.4
Listing 36.13 Using the in-memory database provider to test an EF Core DbContext
[Fact]
public void GetRecipeDetails_CanLoadFromContext()
{
var connection = new SqliteConnection("DataSource=:memory:"); #1
connection.Open(); #2
var options = new DbContextOptionsBuilder<AppDbContext>() #3
.UseSqlite(connection) #3
.Options; #3
using (var context = new AppDbContext(options)) #4
{
context.Database.EnsureCreated(); #5
context.Recipes.AddRange( #6
new Recipe { RecipeId = 1, Name = "Recipe1" }, #6
new Recipe { RecipeId = 2, Name = "Recipe2" }, #6
new Recipe { RecipeId = 3, Name = "Recipe3" }); #6
context.SaveChanges(); #7
}
using (var context = new AppDbContext(options)) #8
{
var service = new RecipeService(context); #9
var recipe = service.GetRecipe (id: 2); #10
Assert.NotNull(recipe); #11
Assert.Equal(2, recipe.Id); #11
Assert.Equal("Recipe2", recipe.Name); #11
}
}
Shows the complete SQLite in-memory test arrangement, including connection opening, DbContext options, EnsureCreated(), and test data. section 36.4

