DbContextOptions is the configuration object that gives an EF Core DbContext its provider, connection, and related services. In tests, it can point the context at a SQLite database held in memory instead of a shared database. section 36.4
Configure a SQLite in-memory context in a few explicit steps:
- Create a SqliteConnection with "DataSource=:memory:" and call Open(); the database lasts while this connection remains open. section 36.4
- Create DbContextOptionsBuilder<AppDbContext>, call UseSqlite(connection), and retrieve the configured Options property. section 36.4
- Pass the options to AppDbContext, call EnsureCreated(), add test data, and use separate context instances when testing reads and writes. section 36.4
SQLite-backed test context
var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlite(connection) .Options; using var context = new AppDbContext(options); context.Database.EnsureCreated(); 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 test pattern, including connection setup, options creation, database preparation, seed data, and context usage. section 36.4
