Data access on the server
Static and Interactive Server pages run on the server, next to the database. One store over EF Core serves both, with no API between the page and the data.
The store
The page asks an interface, and this class answers it
with queries against your DbContext:
public sealed class EfCustomerStore(IDbContextFactory<ShopDb> factory) : ICustomerStore
{
public async Task<IReadOnlyList<CustomerRow>> ListAsync(CancellationToken cancellationToken = default)
{
await using var db = await factory.CreateDbContextAsync(cancellationToken);
return await db.Customers.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new CustomerRow(c.Id, c.Name, c.City))
.ToListAsync(cancellationToken);
}
public async Task<CustomerRow?> GetAsync(int id, CancellationToken cancellationToken = default)
{
await using var db = await factory.CreateDbContextAsync(cancellationToken);
return await db.Customers.AsNoTracking()
.Where(c => c.Id == id)
.Select(c => new CustomerRow(c.Id, c.Name, c.City))
.FirstOrDefaultAsync(cancellationToken);
}
}// Program.cs (server)
builder.Services.AddDbContextFactory<ShopDb>(options => options.UseSqlite(connectionString));
builder.Services.AddScoped<ICustomerStore, EfCustomerStore>();izzy add crud writes a store of this shape for a model you
name.
A context for each call
A static page lives for one request, so its services do too. An Interactive Server page keeps its services
for as long as its circuit. A DbContext injected into that page would stay open for the whole
session, and two event handlers could use it at the same time. The store above creates a context for each
call from an IDbContextFactory, which is safe on static and interactive pages. See Microsoft's
Blazor with EF Core (opens in a new tab).
Next steps
- Data access in the browser: what to add when a page moves to WebAssembly or Auto.
- Data and filters: load a Table or DataGrid's rows from a provider or EF Core.