Introduction
Getting started
One package, one registration and a context factory - then EF Core runs against a SQLite database in the user's browser tab, on the storage backend your preference order picks. Every page after this one runs against that database, in this tab.
Install
Bit.Bsqlite is the whole install: the ADO.NET surface, the EF Core integration, the worker
transport and every storage backend - OPFS, IndexedDB, Cache Storage and in-memory. It targets .NET 10 and
11, each with the EF Core of the same major version. Browser-free unit tests add
Bit.Bsqlite.Testing to the test project.
dotnet add package Bit.BsqliteRegister the services
Register the backends you ship, the order you prefer them in, and the database. The first available backend
wins, but existing data outranks preference: a database created on IndexedDB stays there once OPFS becomes
available. AllowNonPersistentFallback() is what makes in-memory acceptable at all.
using Bit.Bsqlite.Storage.IndexedDb;
using Bit.Bsqlite.Storage.InMemory;
using Bit.Bsqlite.Storage.Opfs;
builder.Services.AddBitBsqliteServices(sqlite => sqlite
.AddStorageProvider<BsqliteOpfsStorageProvider>()
.AddStorageProvider<BsqliteIndexedDbStorageProvider>()
.AddStorageProvider<BsqliteInMemoryStorageProvider>()
.UseStorage(s => s
.Prefer(BsqliteOpfsStorageProvider.ProviderName)
.Fallback(BsqliteIndexedDbStorageProvider.ProviderName)
.Fallback(BsqliteInMemoryStorageProvider.ProviderName)
.AllowNonPersistentFallback())
.AddDatabase("app.db"));
builder.Services.AddBitBsqliteDbContext<AppDbContext>();AddDemoServices
extension method that both Program.cs files call.
Open a context and query
Inject the context factory wherever you would have opened a DbContext. The first context opens
the database and runs the migrations once per session; later ones reuse the session's connection. From there
it is ordinary EF Core - with the async API throughout, because the engine runs in a worker the UI thread
cannot wait on.
@page "/products"
@using Bit.Bsqlite.EntityFrameworkCore
@using Microsoft.EntityFrameworkCore
@inject IBsqliteDbContextFactory<AppDbContext> Contexts
@code {
private List<Product> _products = [];
protected override async Task OnInitializedAsync()
{
// The first context opens the database and applies the migrations; later ones reuse the session.
await using var db = await Contexts.CreateDbContextAsync();
_products = await db.Products.OrderBy(p => p.Name).ToListAsync();
}
private async Task AddAsync()
{
await using var db = await Contexts.CreateDbContextAsync();
db.Products.Add(new Product { Name = "Widget", Price = 19.99m });
await db.SaveChangesAsync();
}
}SaveChanges(), ToList(), DbConnection.Open() -
throw BsqliteSynchronousApiNotSupportedException naming the async overload. The
Limits page runs that on purpose.
Prerendering and render modes
A prerendered page runs once on the server, where there is no browser to open a database in. Open it only once
the page is interactive - RendererInfo.IsInteractive on Interactive WebAssembly, and
OperatingSystem.IsBrowser() on Interactive Auto, where a page on the server circuit is
interactive too. This site renders <Routes> with InteractiveWebAssembly and lets its
SessionLifecycle component do the check for every page.
protected override async Task OnInitializedAsync()
{
// Prerendering runs this on the server first, where there is no browser to open a database in.
// It runs again once the page is interactive on WebAssembly.
if (RendererInfo.IsInteractive is false) return;
await using var db = await Contexts.CreateDbContextAsync();
_orders = await db.Orders.Where(o => o.Status == OrderStatus.Draft).ToListAsync();
}
Interactive Server is not supported: a user's database lives in their browser, and Bsqlite will not keep one
file on the server for every user. A Blazor Hybrid app - MAUI, WPF, Windows Forms - is supported with the same
registration: its database is a SQLite file on the device, on the file-system backend, which is
registered and selected for it automatically.
Lazy loading on WebAssembly
EF Core and Bsqlite are most of what a WebAssembly app downloads for its database - about 2.1 MB, compressed
with Brotli. An app whose database only some pages use can mark them BlazorWebAssemblyLazyLoad,
load them from the router's OnNavigateAsync before those pages render, and leave the registration
out of Program.cs: GetBitBsqliteServices makes the same registration the first time a
page asks in the browser, once for the app, from the one method every page passes it, and still reaches the
app's own services.
// Program.cs registers nothing of Bsqlite's: it runs before the assemblies are there.
// Called only from the pages the assemblies are loaded for - and, to register, from a server
// that prerenders them or a Blazor Hybrid app that shares them: public for those.
public static class AppDatabase
{
// What Program.cs would have registered, unchanged. Pass this one method to
// every call - and register with it in MauiProgram.cs, in a Blazor Hybrid app.
public static void Register(IServiceCollection services)
{
services.AddBitBsqliteServices(sqlite => sqlite
.AddStorageProvider<BsqliteOpfsStorageProvider>()
.AddStorageProvider<BsqliteIndexedDbStorageProvider>()
.UseStorage(s => s
.Prefer(BsqliteOpfsStorageProvider.ProviderName)
.Fallback(BsqliteIndexedDbStorageProvider.ProviderName))
.AddDatabase("app.db"));
services.AddBitBsqliteDbContext<AppDbContext>();
}
public static IBsqliteDbContextFactory<AppDbContext> Contexts(IServiceProvider provider) => provider
.GetBitBsqliteServices(Register)
.GetRequiredService<IBsqliteDbContextFactory<AppDbContext>>();
}
// A page - once it runs in the browser, not while it is prerendered:
@inject IServiceProvider Services
if (RendererInfo.IsInteractive)
{
await using var db = await AppDatabase.Contexts(Services).CreateDbContextAsync();
}@inject LazyAssemblyLoader LazyAssemblyLoader
<Router AppAssembly="typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsync">
...
</Router>
@code {
// Set next to the marks, so unset in an AOT build: loading an assembly that is not marked throws.
private static readonly bool LazyLoadsBsqlite = AppContext.TryGetSwitch("MyApp.LazyLoadsBsqlite", out var on) && on;
private async Task OnNavigateAsync(NavigationContext context)
{
// Every assembly the project file marks BlazorWebAssemblyLazyLoad: Bit.Bsqlite.wasm,
// the EF Core assemblies, what only they use, and the library with your model.
if (LazyLoadsBsqlite && UsesTheDatabase(context.Path))
await LazyAssemblyLoader.LoadAssembliesAsync(DatabaseAssemblies);
}
}Nothing in the host page
The engine (.wasm), the worker and the backends' VFSes are static web assets under
_content/Bit.Bsqlite/, each imported on demand: registering a backend costs nothing until it is
selected, and a session downloads one engine build and the VFS of the backend it selected. There is no script
tag or stylesheet to add.