Skip to Content
TORMMultiple databases, sharding and AOP

Multiple databases, sharding and AOP

On this page

Route connections

using TORM; await using var root = new OrmClient(new List<ConnectionConfig> { new() { ConfigId = "Default", DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=main.db" }, new() { ConfigId = "History", DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=history.db" } }); var history = root.GetConnection("History");

OrmTable.ConfigId selects a configured route. GetClientForEntity<T>() resolves it using entity metadata.

GetConnection returns the current client for an empty or unknown ID. Validate connection IDs at startup and check tenant authorization separately.

Time-based sharding

OrmTable.SplitType and SplitColumn describe the policy; the time property is DateTime. Built-in values include Day, Week, Month, Quarter, Year and Custom. MaxRowCount can participate in capacity policies.

SplitTable() activates entity-based routing for writes. Split(startTime, endTime) limits the physical table range for supported operations. As(tableName) selects a physical table; accept names only from trusted configuration.

Implement ISplitTableService for custom policies and IRowCountSplitTableService for capacity-based behavior. Before enabling CacheSplitTableCatalog or CoordinateSplitTableWrites, define table creation ownership, invalidation and multi-instance coordination.

Limit the time range and table count, and configure matching indexes. Cross-table paging includes reading and merging costs.

Observe execution

db.Aop.OnLogExecuted = (sql, parameters, elapsed) => Console.WriteLine($"SQL completed in {elapsed.TotalMilliseconds:F1} ms"); db.Aop.OnError = (sql, parameters, error) => Console.Error.WriteLine(error.GetType().Name);

OnLogExecuting observes SQL before execution; OnDataExecuting can process values before write parameters are produced. OnTransactionCompletionError reports participant cleanup failures.

Callbacks run on the command path. Avoid blocking network calls and recursive logging into the same database. Redact sensitive parameters before recording them.

Raw ADO

ExecuteNonQueryAsync, ExecuteScalarAsync and ExecuteReaderAsync cover SQL not expressed by query APIs. Build parameters with CreateParameter; treat identifiers as trusted, allow-listed names rather than parameter values.