AutoIncrement = true for auto-generated IDs.Local-First
Data is stored locally in the browser using SQLite, ensuring your app works offline.
Cloud Sync
Optionally sync with Turso Cloud for multi-device and real-time collaboration.
Type-Safe
Entity attributes and strongly-typed DbSets provide compile-time safety.
Auto Schema
Tables and indexes are automatically created from your entity definitions.
Installation
Install the Server package (required)
TursoDb requires Cross-Origin Isolation headers for SharedArrayBuffer support.
Quick Start
Define Your Entities
Use attributes to define how your C# classes map to SQLite tables:Models/User.cs
Create Your Database
Inherit fromTursoDatabase and add TursoDbSet<T> properties for each entity:
Data/AppDatabase.cs
Register and Use
Entity Attributes
[Table] - Define table name
[Table] - Define table name
Maps a class to a specific table name in SQLite.If omitted, the class name is used as the table name.
[PrimaryKey] - Define primary key
[PrimaryKey] - Define primary key
Marks a property as the primary key. Use
[Column] - Define column name
[Column] - Define column name
Maps a property to a specific column name. Use snake_case for SQLite conventions.
[Index] - Create an index
[Index] - Create an index
Creates an index on the column for faster queries. Use
Unique = true for unique constraints.[NotMapped] - Exclude from database
[NotMapped] - Exclude from database
Excludes a property from database persistence.
CRUD Operations
Create
Read
Update
Delete
Query Builder
Build complex queries with the fluent query API:Available Methods
| Method | Description |
|---|---|
Where(clause, params) | Filter results with a SQL WHERE clause |
OrderBy(column) | Sort ascending by column |
OrderByDescending(column) | Sort descending by column |
Take(count) | Limit results to count |
Skip(count) | Skip first count results |
ToListAsync() | Execute and return all results |
FirstOrDefaultAsync() | Execute and return first result or null |
CountAsync() | Return count of matching results |
Transactions
Use transactions for atomic operations that should succeed or fail together:If you dispose the transaction without calling
CommitAsync(), it automatically rolls back.Prepared Statements
For frequently executed queries, use prepared statements for better performance:Raw SQL
Execute raw SQL when you need full control:Turso Cloud Sync
For multi-device sync and cloud backup, useTursoSyncDatabase:
Setup
Data/SyncedAppDatabase.cs
Sync Operations
Sync Events
Subscribe to sync lifecycle events:Sync Options
| Property | Description | Default |
|---|---|---|
SyncUrl | Turso Cloud database URL | Required |
SyncAuthToken | Authentication token | Required |
SyncOnConnect | Sync automatically on connect | true |
SyncIntervalMs | Auto-sync interval (0 = disabled) | 0 |
EncryptionEnabled | Enable local database encryption | false |
EncryptionKey | Encryption key for local database | null |
Cross-Origin Isolation
TursoDb requires Cross-Origin Isolation headers for SharedArrayBuffer support. TheBlazorEssentials.Server
package provides middleware to add these headers.
Basic Configuration
Advanced Configuration
Headers Added
| Header | Value | Purpose |
|---|---|---|
Cross-Origin-Opener-Policy | same-origin | Isolates browsing context |
Cross-Origin-Embedder-Policy | require-corp | Requires resources to grant permission |
Cross-Origin-Resource-Policy | same-origin | Controls resource sharing |
Type Mapping
TursoDb automatically maps C# types to SQLite types:| C# Type | SQLite Type |
|---|---|
int, long, short, byte | INTEGER |
float, double, decimal | REAL |
string | TEXT |
bool | INTEGER (0/1) |
DateTime, DateTimeOffset | TEXT (ISO 8601) |
Guid | TEXT |
byte[] | BLOB |
Best Practices
Use dependency injection
Use dependency injection
Register your database as a scoped service for proper lifecycle management:
Connect once, early
Connect once, early
Connect to the database early in your app lifecycle, such as in
App.razor or a layout component:Handle sync conflicts
Handle sync conflicts
When using cloud sync, implement conflict resolution strategies for your use case.
Consider using timestamps or version numbers to detect conflicts.
Troubleshooting
Third-party scripts not loading
Third-party scripts not loading
Cross-Origin Isolation may break external scripts. Options:
- Use
options.CoepPolicy = "credentialless"for less strict isolation - Add script paths to
options.ExcludePaths - Ensure external resources have
Cross-Origin-Resource-Policyheaders
Sync authentication failed
Sync authentication failed
Verify your Turso Cloud credentials:
- Check
SyncUrlformat:libsql://[db-name]-[org].turso.io - Ensure
SyncAuthTokenis valid and not expired - Verify the database exists in your Turso dashboard
API Reference
TursoDatabase
Base class for local databases
TursoSyncDatabase
Sync-enabled database with Turso Cloud
TursoDbSet
Typed collection for entity CRUD operations
TursoQueryBuilder
Fluent query builder API