UseSqlite() configures Entity Framework Core to use SQLite as the database provider for a DbContext. The Microsoft.EntityFrameworkCore.SQLite package supplies the extension method, which accepts either a connection string or an existing SQLite connection. section 12.2.3 section 36.4
Listing 12.4 Registering a DbContext with the DI container
using Microsoft.EntityFrameworkCore;
WebApplicationBuillder builder = WebApplication.CreateBuilder(args);
var connString = builder.Configuration #1
.GetConnectionString("DefaultConnection"); #1
Builder.Services.AddDbContext<AppDbContext>( #2
options => options.UseSqlite(connString)); #3
WebApplication app = builder.Build();
app.Run();
Register AppDbContext with dependency injection, load the connection string from configuration, and select SQLite with UseSqlite(). section 12.2.3
UseSqlite() supports two common configurations:
- For an application database, call options.UseSqlite(connString) inside AddDbContext<AppDbContext>. Load the connection string from configuration so environments can use different databases. section 12.2.3
- For isolated tests, create a SqliteConnection with DataSource=:memory:, open it, and pass it to UseSqlite(). Keep the connection open while multiple DbContext instances share the database. section 36.4 section 36.5
- The in-memory database disappears when its SQLite connection closes. Calling context.Database.EnsureCreated() prepares the temporary database before adding or querying entities. section 36.4 section 36.5
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 section 36.5
