SqliteConnection is the Microsoft.Data.Sqlite connection type used to create an isolated SQLite database for EF Core tests. Construct it with "DataSource=:memory:" and open it before creating the DbContext. section 36.4
Use the connection in this sequence:
- Create a SqliteConnection with the "DataSource=:memory:" connection string. section 36.4
- Call Open() yourself so the database remains available while multiple DbContext instances use it. section 36.5
- Pass the open connection to DbContextOptionsBuilder<AppDbContext>.UseSqlite(). section 36.4
- Pass the resulting options to AppDbContext and call EnsureCreated() before using the test data. section 36.5
The database exists only while the connection stays open. Closing or disposing the connection destroys the in-memory database, while manually opening it allows several DbContexts to share the same isolated test database. section 36.4 section 36.5
Testing with an in-memory SQLite connection
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(); // Add test entities and exercise the service. }
