Database: Getting Started
- Introduction
- Complete Example: Transaction Rollback
- Running SQL Queries
- Database Transactions
- Checking the Schema
Introduction
DotBlaze talks to databases through Entity Framework Core. You rarely touch EF directly: models use the Eloquent-style active record API, the DB facade runs raw SQL and simple table queries, and the Schema builder writes migrations. Four databases are supported:
- SQLite (built in)
- PostgreSQL (
pgsql) - MySQL (
mysql) - SQL Server (
sqlsrv)
Configuration
The database configuration lives in config/Database.cs. default names the connection used when nothing else is specified, and connections defines every connection:
public class DatabaseConfig : ConfigFile
{
public override object Values() => new
{
@default = Env("DB_CONNECTION", "sqlite"),
connections = new
{
sqlite = new { driver = "sqlite", database = Env("DB_DATABASE", "database/app.db") },
pgsql = new { driver = "pgsql", host = Env("DB_HOST", "127.0.0.1"), port = Env("DB_PORT", 5432), database = Env("DB_DATABASE", "dotblaze"), username = Env("DB_USERNAME", "postgres"), password = Env("DB_PASSWORD") },
mysql = new { driver = "mysql", host = Env("DB_HOST", "127.0.0.1"), port = Env("DB_PORT", 3306), database = Env("DB_DATABASE", "dotblaze"), username = Env("DB_USERNAME", "root"), password = Env("DB_PASSWORD") },
sqlsrv = new { driver = "sqlsrv", host = Env("DB_HOST", "127.0.0.1"), port = Env("DB_PORT", 1433), database = Env("DB_DATABASE", "dotblaze"), username = Env("DB_USERNAME", "sa"), password = Env("DB_PASSWORD") },
},
};
}Set DB_CONNECTION in .env to choose the default connection. DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD supply its connection details through Env, see Configuration. Missing or empty values use the defaults in the config class, so the example .env leaves DB_PORT, DB_DATABASE, and DB_USERNAME empty.
The DB_* variables are shared by the connection definitions. To configure connections separately, edit their values in config/Database.cs or use environment overrides such as database__connections__pgsql__host=db.internal. Like any configuration value, the default connection can also be overridden with database__default=pgsql.
Each connection accepts these keys:
| Key | Used by | Description |
|---|---|---|
driver | all | sqlite, pgsql, mysql, or sqlsrv. Defaults to the connection name. |
connection_string | all | A full ADO.NET connection string. When present, the other keys below are ignored. |
database | all | Database name. For SQLite, a file path relative to the project root (default database/app.db). |
host | pgsql, mysql, sqlsrv | Defaults to 127.0.0.1. |
port | pgsql, mysql, sqlsrv | Defaults to 5432, 3306, and 1433. |
username, password | pgsql, mysql, sqlsrv | Credentials. |
trust_server_certificate | sqlsrv | true to accept a self-signed certificate (local development). Defaults to false. |
When default is missing, DotBlaze uses a connection named sqlite. A sqlite connection works even when it is not listed in the file; any other undefined connection name throws an InvalidOperationException.
SQLite
The SQLite driver creates the directory of the database file if needed and turns foreign key enforcement on (Foreign Keys=True). An absolute path is used as-is.
Database Drivers
SQLite ships with the core DotBlaze package. The other drivers live in separate packages so applications only pull in the database client they use:
| Driver | Package | Built on |
|---|---|---|
sqlite | DotBlaze | Microsoft.EntityFrameworkCore.Sqlite |
pgsql | DotBlaze.Database.Postgres | Npgsql |
mysql | DotBlaze.Database.MySql | Oracle's MySql.EntityFrameworkCore |
sqlsrv | DotBlaze.Database.SqlServer | Microsoft.Data.SqlClient |
Add the package and set the driver name in the config; DotBlaze loads the package automatically based on the driver name. You don't register anything:
dotnet add package DotBlaze.Database.PostgresIf the package is missing, the first database call fails with a message telling you which package to add.
NOTE
The MySQL driver uses Oracle's official EF Core provider because Pomelo has no EF Core 10 release yet.
Where the Database Can Be Used
Models and the DB facade use the active service scope. Inside an HTTP request, a queued job, a seeder, or a console command this happens automatically. Each scope gets its own DbContext per connection, shared by every model and DB call in that scope.
In other background code (a hosted service, a test) open a scope yourself with ServiceScope.Run:
await ServiceScope.Run(app.Services, async () =>
{
var count = await User.Query().Count();
});Without a scope, facades throw InvalidOperationException: No active service scope.
Running SQL Queries
The DB facade runs raw SQL. Bindings are written as {0}, {1}, ... and are always sent as parameters, never pasted into the SQL text.
Running a Select Query
DB.Select<T> maps every row to a new T. Columns are matched to settable properties ignoring case and underscores, so is_active fills IsActive. Columns without a matching property are skipped:
public sealed class AuthorRow
{
public long Id { get; set; }
public string Name { get; set; } = "";
public bool IsActive { get; set; }
}
var rows = await DB.Select<AuthorRow>("SELECT id, name, is_active FROM authors WHERE name = {0}", "Renamed");Without a type argument, DB.Select returns one Dictionary<string, object?> per row. The dictionaries are case-insensitive and NULL becomes null:
var rows = await DB.Select("SELECT * FROM users WHERE id > {0}", 10);
var name = rows[0]["name"];Running a General Statement
DB.Statement runs INSERT, UPDATE, DELETE, or DDL statements and returns the number of affected rows:
var affected = await DB.Statement("UPDATE users SET name = {0} WHERE id = {1}", "Ali", 1);For simple WHERE/ORDER BY queries without writing SQL, see the query builder.
Using Multiple Database Connections
DB.Connection(name) returns a DatabaseConnection with the same methods (Select, Statement, Table, Transaction) for a connection defined in config/Database.cs:
var users = await DB.Connection("pgsql").Select("SELECT * FROM users");Context on the returned connection gives you the underlying EF Core DbContext (DotBlazeDbContext) if you need it.
Models choose their connection with the [Connection] attribute, see Database Connections.
Database Transactions
DB.Transaction runs a closure in a transaction. It commits when the closure finishes and rolls back when it throws; the exception is rethrown:
await DB.Transaction(async () =>
{
await order.Save();
await DB.Table("stock").Where("product_id", order.ProductId).Update(new { reserved = true });
});Models on the same connection share the scope's DbContext, so model saves inside the closure take part in the transaction. A DB.Transaction inside another one joins the outer transaction instead of starting a new one.
DB.Transaction uses the default connection. For another connection use DB.Connection("pgsql").Transaction(...).
DB.AfterCommit runs code once the current transaction commits, and never if it rolls back (without a transaction, right away). Events that implement IShouldDispatchAfterCommit use it:
await DB.Transaction(async () =>
{
await order.Save();
await DB.AfterCommit(() => Cache.Forget("orders.count"));
});NOTE
A job dispatched to the database queue inside a transaction on the same connection is inserted in that transaction, so it disappears when the transaction rolls back. For other connections, use AfterCommit().
Checking the Schema
DotBlaze does not generate the database schema from your models: tables come from migrations, and models describe them. The db:check command compares the two and reports tables or columns a model uses that do not exist in the database:
dotblaze db:check [sqlite] table 'orphan_rows' (Orphan) does not exist
[sqlite] column 'posts.published_at' (Post.PublishedAt) does not exist
2 problem(s) found.The command exits with code 1 when problems are found, so it can run in CI after migrate. It does not report extra columns in the database that no model uses.
Complete Example: Transaction Rollback
Use the Blog application and sibling test project. This complete test verifies that an exception rolls back a model save, not merely that the callback throws:
// Blog.Tests/TransactionTest.cs
using Blog.Models;
using DotBlaze;
using DotBlaze.Testing;
using Xunit;
namespace Blog.Tests;
public class TransactionTest
{
[Fact]
public async Task Failed_work_does_not_leave_a_user_row()
{
using var app = new TestApp<Program>();
await app.RefreshDatabase();
await Assert.ThrowsAsync<InvalidOperationException>(() => app.Run(() =>
DB.Transaction(async () =>
{
await User.Create(new
{
Name = "Rollback example",
Email = "rollback@example.test",
Password = "local-example-password",
});
throw new InvalidOperationException("Simulated application failure.");
})));
await app.AssertDatabaseMissing("users", new { email = "rollback@example.test" });
}
}Run dotnet test Blog.Tests --filter FullyQualifiedName~TransactionTest from the parent directory. Expected: one passing test with no row retained. Real network effects are not rolled back by a database transaction; use DB.AfterCommit or a job's AfterCommit() when dispatch depends on committed data.