liveBook · Manning

UseSqlite()

As explained in ASP.NET Core in Action, 3e

UseSqlite() is an Entity Framework Core configuration method that selects SQLite as the database provider for a context.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains package setup, dependency-injection registration, connection handling, and in-memory lifetime behavior.
Examples
Uses ASP.NET Core registration and a SqliteConnection backed by DataSource=:memory: for isolated tests.
What it assumes
Assumes an EF Core DbContext and teaches the required SQLite package, options configuration, and connection setup.
What you can do after
Apply EF Core SQLite configuration to application contexts or create fast isolated test databases.
How it connects
Connects SQLite configuration with EF Core, DbContext, dependency injection, connection strings, and database testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.