In version 5+, SqliteInMemory.CreateOptions<T> disposes the connection when the context is disposed. If your tests use multiple DbContext instances with the same options, the second instance will find an empty database. Use one of the following four strategies to resolve this:
1. Quick and Easy: Turn off Dispose
Use options.TurnOffDispose() to restore the behavior of previous versions where the connection persists.
2. Best Approach: Single Instance with ChangeTracker.Clear()
Instead of multiple DbContext instances, use a single instance and call context.ChangeTracker.Clear() to remove tracked entities. This is the recommended approach as it allows for cleaner code using using var context = ....
3. Keep multiple using blocks: Use StopNextDispose()
If you must use multiple using blocks, call options.StopNextDispose() immediately after creating the options. This prevents the first DbContext from disposing the underlying connection.
4. Many DbContext instances: Manual Dispose
If you have many instances, turn off automatic disposal and call options.ManualDispose() at the very end of your test.
// Strategy 1: Turn off Dispose
var options = SqliteInMemory.CreateOptions<BookContext>();
options.TurnOffDispose();
// Strategy 2: Best approach (Single instance)
var options = SqliteInMemory.CreateOptions<BookContext>();
using var context = new BookContext(options);
context.Database.EnsureCreated();
context.SeedDatabaseFourBooks();
context.ChangeTracker.Clear(); // Clears tracked entities so next query hits DB
var books = context.Books.ToList();
// Strategy 3: Stop next dispose
var options = SqliteInMemory.CreateOptions<BookContext>();
options.StopNextDispose();
using (var context = new BookContext(options)) { /* ... */ }
using (var context = new BookContext(options)) { /* ... */ }
// Strategy 4: Manual Dispose
var options = SqliteInMemory.CreateOptions<BookContext>();
options.TurnOffDispose();
using (var context = new BookContext(options)) { /* ... */ }
using (var context = new BookContext(options)) { /* ... */ }
options.ManualDispose();