redb capabilities

redb stores typed .NET objects in a relational database: PostgreSQL, Microsoft SQL Server or SQLite. A scheme is a plain C# class, synchronised with the database at start, so a new property needs no migration. Saving, loading, LINQ queries, trees, reference lists, aggregates and window functions all go through one service, IRedbService.

Unless a line says otherwise, a fact holds on every engine and in both editions, Free and Pro.

Storage model and schemes

An object is a RedbObject<TProps>: a set of base fields plus your own Props class. Schemes are declared in code and kept in step with the database.

  • RedbObject<TProps> carries base fields (id, name, parent, owner, dates, hash) and a plain C# Props class.
  • Schemes are code-first: [RedbScheme("name")] on the Props class.
  • IRedbService.InitializeAsync() synchronises every scheme at start; SyncSchemeAsync<TProps>() synchronises one class.
  • AutoSyncSchemesOnSave (on by default) creates a missing scheme on the first save.
  • [RedbRename("OldName")] renames a stored property and keeps its values.
  • MigrateStructureTypeAsync changes the stored type of a property.
  • DropUnknownStructuresAsync<TProps> removes stored properties the class no longer has.
  • GetSchemeByTypeAsync, GetSchemesAsync and GetStructureTreeAsync read scheme metadata.
  • EnsureDatabaseAsync creates the redb schema; GetSchemaScript and GetUpgradeScript return the SQL for running it by hand.
  • CheckSchemaAsync and the SchemaProblems property report a schema that does not match the build.
  • CheckBaseIndexesAsync reports missing or invalid base indexes; RepairBaseIndexesAsync builds them.
  • Object and scheme hashes are the same on the server and in the browser (RedbMd5, a managed MD5 where the platform has none).

What a Props class may hold

Fields

  • Every public instance property with a getter is a field.
  • [RedbIgnore] leaves a property out; [JsonIgnore] does not.
  • Indexers are skipped.
  • [RedbAlias("...")] gives a field a display alias; [RedbRename(...)] renames a stored field in place; [RedbTags]; [RedbUnique] (see Uniqueness).
  • Inherited public properties are fields; a record class counts as a class.
  • A non-nullable reference type or a non-Nullable value type marks the structure as required.

Scalars

  • string, char, bool, int, long, short, byte, double, float, decimal, Guid, byte[] (one value, not an array of bytes).
  • DateTime (a clock reading: it returns the same wall time anywhere), DateTimeOffset (an instant), DateOnly (a date), TimeOnly and TimeSpan (stored as ticks).
  • Nullable forms of all value types (int?, DateTime?, Guid? and so on).
  • enum and enum? are stored as the member name in text; filters compare by name.
  • An enum cannot be a [RedbUnique] key (RedbUniqueKeyDefinitionException).
  • The object field ValueString (not a Props field) holds up to 450 characters; a longer value raises RedbValueStringTooLongException.

Nested classes

  • A class of your own (not in a System namespace) is a nested class, to any depth.
  • Fields of nested classes are paths in queries (HomeAddress.Details.Floor).

Collections

  • Collection types: T[], List<T>, IList<T>, ICollection<T>, IEnumerable<T>.
  • Element types: any scalar, a nested class, RedbObject<T>, RedbListItem.
  • Collections can sit inside nested classes and inside dictionary values.
  • Refused at scheme sync and at save: HashSet<T>, Queue<T> and other framework collections (RedbUnsupportedCollectionException, which names the allowed types).
  • Refused: a collection directly inside a collection, and multi-dimensional arrays (RedbNestedCollectionException: wrap the inner collection in a class).

Dictionaries

  • Dictionary<TKey, TValue> and IDictionary<TKey, TValue>.
  • Key types: string, char, int, long, short, byte, double, float, decimal, bool, DateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan, Guid, byte[], enums (by name), value tuples and classes (stored as encoded JSON).
  • Tuple keys: Dictionary<(int Year, string Quarter), string> and other ValueTuple shapes.
  • Value types: a scalar, a nested class (with its own arrays and dictionaries), RedbObject<T>, RedbListItem.
  • A dictionary value that is itself a collection is refused (RedbNestedCollectionException); put it in a class.
  • A key longer than the provider limit raises RedbDictionaryKeyTooLongException.
  • A stored key that no longer reads as the key type (for example a renamed enum member) raises RedbDictionaryKeyException.
  • A read lists entries by key: strings ordinally, numbers and dates by value, tuple and class keys by their stored text.

References

  • A RedbObject<T> property, arrays and lists of RedbObject<T>, and dictionaries with RedbObject<T> values: the whole graph is saved and loaded in one call.
  • A referenced object that is already in the database is written as its id; it is not inserted or changed.

Lists

  • A RedbListItem property, nullable, arrays and lists of items, dictionaries with item values (see Reference lists).

How each shape is queried (differences from scalars)

  • A nested class field: filter, sort, group, window and select like a scalar.
  • An array of scalars: Contains, Any(), Count/Length, an element by index (Pro only), GroupByArray, array aggregates.
  • An array of classes: Any(predicate) (Pro only), an element field by index (Pro only), GroupByArray by an element field.
  • An array of list items: Any(r => r.Value/Alias/Id == ...), with == only.
  • A dictionary: the indexer with a constant or variable key (tuple keys too), ContainsKey, a field of a class value (Dict["HQ"].City). A dictionary entry cannot be a sort key or a window key.
  • A whole collection as a key (DistinctBy, GroupBy keys): the collection folded in index order.

Save, load, delete

One call saves or loads a whole object with its Props.

  • SaveAsync saves one object or many; LoadAsync<TProps> loads by id; LoadJsonAsync returns the stored object as JSON.
  • AddNewObjectsAsync inserts new objects in bulk (see Batch operations).
  • DeleteAsync deletes for good; SoftDeleteAsync moves objects to the trash; PurgeTrashAsync and DeleteWithPurgeAsync empty it.
  • GetDeletionProgressAsync follows a long purge.
  • LockForUpdateAsync and LockForUpdateRequiredAsync lock objects for update inside a transaction.
  • LoadWithParentsAsync<TProps> loads an object with its chain of parents.
  • IRedbSaveInterceptor runs your code on every save.
  • PropsSaveStrategy.DeleteInsert (the default): a save rewrites all value rows of the object.
  • PropsSaveStrategy.ChangeTracking (Pro only): a save compares with the stored value tree and writes only the changed values; an object whose hash is unchanged skips the value writes. The Free providers refuse it with NotSupportedException.

Batch operations

  • SaveAsync(IEnumerable<IRedbObject>): one call for new and existing objects of any schemes, nested objects included; returns the ids of the top objects.
  • A batch save runs in one transaction of its own, or inside the caller's transaction (explicit or TransactionScope). There a unique violation rolls back to a savepoint and leaves the caller's transaction usable.
  • AddNewObjectsAsync(objects[, user]): new objects only, no permission check, ids generated where id == 0, nested objects and arrays included; a referenced existing object is written as its id.
  • Bulk insert: binary COPY on PostgreSQL; on SQL Server a multi-row INSERT up to 250 rows and SqlBulkCopy above that; on SQLite a chunked multi-row INSERT in one transaction.
  • BulkInsertTimeout: the time limit of one COPY or SqlBulkCopy.
  • LoadAsync(IEnumerable<long> ids, depth): objects of different schemes in one call.
  • LoadWithParentsAsync(ids, depth): many objects with their parent chains.
  • DeleteAsync(IEnumerable<long> ids) and DeleteAsync(IEnumerable<IRedbObject>): one statement; returns the count.
  • query.DeleteAsync(): deletes by filter.
  • SoftDeleteAsync(ids | objects, trashParentId): moves objects and their descendants under a trash container at once, so they leave queries; returns DeletionMark(TrashId, MarkedCount).
  • PurgeTrashAsync(trashId, totalCount, batchSize = 10, progress) and DeleteWithPurgeAsync(ids, batchSize = 10, progress, trashParentId): physical delete in portions, with progress.
  • GetDeletionProgressAsync(trashId) and GetUserActiveDeletionsAsync(userId) return PurgeProgress(TrashId, Deleted, Remaining, Status, StartedAt, UserId).
  • IBackgroundDeletionService.DeleteAsync: soft delete now, purge later by a polling worker.
  • GetOrphanedDeletionTasksAsync and TryClaimOrphanedTaskAsync make the background purge safe across cluster nodes.
  • LockForUpdateAsync(ids) and LockForUpdateRequiredAsync(ids): row locks on many objects inside a transaction.
  • ListProvider.AddItemsAsync and SaveListWithItemsAsync: many list items in one call.
  • There is no bulk update by query: changes go through SaveAsync of loaded objects.

Lazy loading

  • LoadAsync<T>(id, depth = 10) and LoadAsync(ids, depth): references to other objects are loaded eagerly down to depth.
  • WithPropsDepth(depth) on a query: the depth of nested RedbObject loading for that query.
  • WithMaxRecursionDepth(depth): the depth limit of nested and/or/not in a filter (default 10).
  • A reference that was not loaded comes back as a stub: the id is set, Props are not loaded.
  • The first read of a stub's Props loads exactly that object; its own references are stubs again.
  • EnableLazyReferences (default false): references whose property is declared virtual (RedbObject<T> or a collection of them) come back as stubs at any depth; virtual on a scalar or a nested class is ignored.
  • WithLazyReferences(bool) per query (Free only): overrides the global switch. With the Pro packages it has no effect and the global switch applies.
  • LazyReferenceAccess.Blocking (default): the Props getter of a stub loads synchronously on the thread pool, with no deadlock under a SynchronizationContext.
  • LazyReferenceAccess.Throw: the getter throws RedbSynchronousLazyLoadException; meant for Blazor WebAssembly and UI hosts.
  • RedbObject<T>.LoadPropsAsync() and IsPropsLoaded: an explicit asynchronous load of a stub.
  • LoadReferencesAsync(parent, p => p.Refs) and (parent, p => p.Ref): load a collection of stubs in one batch query; loaded ones are skipped; a target in the trash gives null Props.
  • LoadLinkedObjectsAsync(items): the linked objects of list items in one query.
  • Outside a live scope: LazyLoadWithoutScope.Refuse (default) throws RedbLazyLoadScopeEndedException; FreshScope opens a scope and a pooled connection per load and warns when the rate gets high.
  • A hand-made reference (new RedbObject<T> { id = x }) saved as a reference raises RedbUnloadedReferenceException instead of overwriting the target; its Props read null.
  • With the props cache, a cached graph is shared by all scopes; its stubs load on the reader's scope, never on the scope that cached it.

Queries

Entry points

  • Query<T>() and Query<T>(user).
  • TreeQuery<T>() and TreeQuery<T>(rootId | root | rootIds | roots, maxDepth), each with a user overload.

Filter

  • Where(p => ...); chained Where calls combine with AND.
  • WhereRedb(o => ...) filters on base fields.
  • WhereIn(selector, values) and WhereInRedb(selector, values) translate to SQL IN.
  • Base fields for the *Redb methods: Id, SchemeId, Name, ParentId, OwnerId, WhoChangeId, DateCreate, DateModify, DateBegin, DateComplete, Key, ValueLong, ValueString, ValueGuid, ValueBool, ValueDouble, ValueNumeric, ValueDatetime, ValueBytes, ValueUnique, Note, Hash.

Inside a filter

  • ==, !=, <, <=, >, >=; &&, ||, !; boolean fields alone and negated.
  • == null, != null; nullable .HasValue and .Value.
  • SQL null semantics: a field without a value matches neither == nor !=.
  • Arithmetic + - * / % between fields and constants; unary minus.
  • Conditional c ? a : b and coalesce a ?? b.
  • Math.Abs, Round (with digits), Floor, Ceiling, Truncate, Sqrt, Sign, Exp, Log, Log(x, base), Log10, Pow.
  • String Contains, StartsWith, EndsWith, each with StringComparison; the IgnoreCase forms search without case.
  • String ToLower, ToLowerInvariant, ToUpper, ToUpperInvariant, Trim, TrimStart, TrimEnd, Length.
  • String Substring(start[, length]), Replace(old, new), IndexOf(value), PadLeft/PadRight(width[, char]).
  • Other string members are refused with NotSupportedException ("String method X is not supported").
  • Regex.IsMatch(input, pattern[, RegexOptions.IgnoreCase]) and Regex.Replace(input, pattern, replacement): PostgreSQL ~ / ~*, SQLite built-in functions; on SQL Server they need SQL Server 2025 (compatibility level 170).
  • DateTime and DateTimeOffset members Year, Month, Day, Hour, Minute, Second, DayOfWeek, DayOfYear.
  • DateTime and DateTimeOffset AddDays, AddMonths, AddYears, AddHours, AddMinutes, AddSeconds.
  • DateOnly, TimeOnly, TimeSpan: comparison and ranges.
  • Guid, enum (compared by name), bool and their nullable forms.
  • Contains on a local collection (array, List, IEnumerable, span overload) translates to IN; a null in the list is ignored.
  • A stored collection: Contains(value), Any(), Count / Length compared with a number.
  • Any(predicate) over an array of classes (Pro only): every condition reads the same element; comparisons, null checks, Contains of a list, &&, ||, !. The Free providers refuse it.
  • An element by index arr[i] and arr[i].Field, with a non-negative constant or variable (Pro only); past the end means no value. Refused in sort, group and window keys.
  • Dictionary indexer dict[key] (tuple keys too), dict[key].Field, dict.ContainsKey(key).
  • Nested class paths of any depth.
  • List item fields: Status.Value, Status.Alias, Status.Id, and Status == item (by id).
  • Sql.Function<T>("NAME", args...): any SQL function by name; the arguments must be inline, not a variable array.
  • A method call inside a field path (First(), ElementAt()) is refused with a message naming the allowed forms.
  • StringCollation names a collation for case folding beyond ASCII in case-insensitive search. It applies on PostgreSQL and SQLite only; the default collation of SQL Server already ignores case.

Paging and order

  • Take, Skip; OrderBy, OrderByDescending, ThenBy, ThenByDescending; *Redb forms for base fields.
  • Order keys: field paths, arithmetic of fields, unary minus, string functions (ToLower, ToUpper, Trim and others), list item Value/Alias.
  • Rows without a value come first in ascending order and last in descending order, on every engine.

Distinct

  • Distinct(): in Free one row per object; in Pro one object per Props hash.
  • DistinctBy(key) and DistinctByRedb(key): one object per key.
  • In Pro, DistinctBy combines with OrderBy (key first), Skip/Take, and CountAsync counting the keys.

Results and existence

  • ToListAsync, FirstOrDefaultAsync(), FirstOrDefaultAsync(predicate), CountAsync, AnyAsync(), AnyAsync(predicate), AllAsync(predicate).

Projection

  • Select(x => new { ... }) over RedbObject<T>: anonymous types, nested fields, arrays; reads only the selected structures.
  • On a projection: Where, OrderBy, OrderByDescending, ThenBy, ThenByDescending, Take, Skip, Distinct, ToListAsync, CountAsync, FirstOrDefaultAsync, GetProjectionInfoAsync.

Aggregates

  • SumAsync, AverageAsync, MinAsync, MaxAsync with a selector over Props.
  • SumRedbAsync, AverageRedbAsync, MinRedbAsync, MaxRedbAsync over base fields.
  • GetStatisticsAsync(selector): Sum, Average, Min, Max and Count in one query.
  • AggregateAsync(x => new { ... }) and AggregateRedbAsync: several aggregates in one query with Agg.Sum, Agg.Average, Agg.Min, Agg.Max, Agg.Count().
  • Over array elements: Agg.Sum/Average/Min/Max/Count(x.Props.Arr.Select(...)).
  • A field of an element of a class array by index inside an aggregate (Pro only).

Grouping

  • GroupBy(key) and GroupByRedb(key): one field or an anonymous type of fields; a list item or its field as the key.
  • GroupByArray(arraySelector, keySelector): by an element field, the element itself, a nested class of the element, or SelectMany over an inner array.
  • On a group: SelectAsync(g => new { g.Key, Agg.Sum(g, x => x.F), Agg.Average, Agg.Min, Agg.Max, Agg.Count(g), Agg.Count(g, predicate) }), CountAsync, Having(predicate), WithWindow, ToSqlStringAsync.
  • Conditions in Agg.Count(g, predicate): comparisons, &&, ||, !, null tests, boolean fields.
  • Refused with NotSupportedException in grouping: computed keys or aggregates, string methods in a condition, dictionaries in the array path, arrays of list items or references.

Window functions

  • WithWindow(w => w.PartitionBy(...).OrderBy(...).OrderByDesc(...).Frame(...)).SelectAsync(...); PartitionByRedb, OrderByRedb, OrderByDescRedb.
  • Win.RowNumber, Rank, DenseRank, Ntile(n), Sum, Avg, Count, Min, Max, Lag, Lead, FirstValue, LastValue.
  • Frames: Frame.Rows(n), Frame.Rows(), Frame.Range(); bounds Preceding(n), UnboundedPreceding, CurrentRow, Following(n), UnboundedFollowing.
  • Where before a window.
  • Skip/Take with a window (Pro only): the window is computed over the whole filtered set, and the page is returned.
  • GroupBy(...).WithWindow(...) and GroupByArray(...).WithWindow(...): windows over aggregated groups.

Trees

Tree operators work on TreeQuery and combine with every operator above.

  • WhereRoots, WhereLeaves, WhereLevel(n), WhereLevel(l => ...), WhereChildrenOf(id | obj), WhereDescendantsOf(id | obj, maxDepth).
  • WhereHasAncestor<T>(predicate), WhereHasDescendant<T>(predicate).
  • WithMaxDepth(depth): the tree search depth (default 50 for descendants, 1 for children).
  • ToTreeListAsync (with parent chains), ToRootListAsync (with recursive children), ToFlatListAsync.
  • GroupBy and WithWindow inside a subtree.
  • AnyAsync on a tree stops at the first match (Pro only).
  • Tree services: CreateChildAsync, LoadTreeAsync(root, maxDepth), GetChildrenAsync, GetDescendantsAsync, GetPathToRootAsync, MoveObjectAsync (with a cycle check), DeleteSubtreeAsync, LoadWithParentsAsync.
  • Polymorphic trees, whose nodes have different Props classes: LoadPolymorphicTreeAsync, GetPolymorphicChildrenAsync, GetPolymorphicDescendantsAsync, GetPolymorphicPathToRootAsync.
  • In memory: DepthFirstTraversal, BreadthFirstTraversal, PostOrderTraversal, FlattenWithLevels, FindNodes, FindById, GetLeaves, GetNodesAtLevel, IsBalanced, GetMaterializedPath, CreateHierarchicalPath.
  • Database checks without loading the tree: IsDescendantOfAsync, IsAncestorOfAsync, IsLeafAsync, GetChildrenCountAsync, GetDescendantsCountAsync, GetTreeLevelAsync.

Delete by query

  • query.DeleteAsync() deletes every object the query selects and returns the count.

Diagnostics

  • ToSqlString(), ToSqlStringAsync(), ToFilterJsonAsync(), ToAggregateSqlStringAsync, and ToSqlStringAsync(selector) on grouped and windowed queries.
  • WithQueryPlanner(bool) for a block of code (Pro only).

How a query runs

  • Free runs queries through the SQL module installed in the database: PL/pgSQL on PostgreSQL, T-SQL on SQL Server, a native loadable extension on SQLite.
  • Pro builds the SQL in C# and materialises Props in parallel.
  • The query planner is Pro only (EnablePvtPrefilter, on by default). It reads a page, a count or an aggregate without pivoting every object of the scheme; using (redb.WithQueryPlanner(false)) turns it off for one block of code.

Reference lists

Model

  • RedbList: Id, Name, Alias, Items; RedbList.Create(name, alias), AddItem(value[, idObject | linkedObject], alias), CreateItem, RemoveItem, FindItemByValue, the indexer list["value"], ClearItems, SetItems.
  • RedbListItem: Id, IdList, Value, Alias, IdObject, Object (the linked object), IsObjectLoaded, IsObjectReference, GetObjectAsync(), GetDisplayValue(); RedbListItem.ForList(list, value, alias, idObject | linkedObject).
  • An item can carry a linked RedbObject of any scheme (IdObject / Object, an untyped IRedbObject) as an extension object of the item.
  • PreloadListItemLinkedObjects (default true): items returned by list reads come with their linked objects, loaded in one batch; false leaves Object lazy.
  • RedbListItem.Object read lazily outside a live scope follows LazyLoadWithoutScope; LoadLinkedObjectsAsync(items) loads the linked objects in one query.

Provider (IRedbService.ListProvider)

  • GetListAsync(id), GetListByNameAsync(name), GetAllListsAsync, GetListWithItemsAsync(id), GetListByNameWithItemsAsync(name).
  • SaveListAsync, SaveListWithItemsAsync, DeleteListAsync, IsListUsedInStructuresAsync.
  • GetListItemAsync(id), GetListItemsByIdsAsync(ids), GetListItemsAsync(listId), GetListItemByValueAsync(listId, value), GetItemsByObjectReferenceAsync(objectId).
  • SaveListItemAsync, DeleteListItemAsync, AddItemsAsync(list, items) and AddItemsAsync(list, values, aliases).
  • SyncListFromEnumAsync<TEnum>(listName): a list whose items follow the members of an enum.

In Props

  • RedbListItem, RedbListItem?, arrays and lists of items, dictionaries with item values.

Queries

  • Filter by Value, Alias, Id, or by the item itself (by id); WhereIn on Value.
  • Any over an item array: Value/Alias/Id with == only, other operators are refused; !Any includes empty and missing arrays.
  • Sort by Status.Value or Status.Alias.
  • GroupBy by an item (the key is filled with the item: Id, Value, Alias) or by its Value/Alias.
  • GroupByArray over item arrays is refused.
  • SQL Server, Free only: a negated comparison of an item's Id/Value/Alias also returns objects without an item.

Cache

  • Lists and items are cached per cache domain (EnableListCache, ListCacheTtl); writes through the provider invalidate the cache locally.

Caches

Props cache

  • EnablePropsCache (default false) keeps whole RedbObject<T> graphs (base fields and Props) in process memory; a hit costs no Props read.
  • A hit is validated by the object hash: the load reads the stored Hash and serves the cached graph only if it matches.
  • SkipHashValidationOnCacheCheck (default false): true serves a hit without asking the database. This applies outside a transaction only; inside any transaction (explicit or TransactionScope) the hash is always checked.
  • PropsCacheMaxSize (default 10000, max 10,000,000): when the cache is full, the least recently used tenth is evicted at once.
  • A "Props cache is full" warning is logged when evictions happen within the diagnostic window, naming PropsCacheMaxSize; slow hit validation also logs a warning.
  • PropsCacheTtl (default 60 minutes, max 7 days): an entry older than the TTL counts as stale.
  • Invalidation: every save, delete, batch delete, tree delete and tree move removes the objects it touched from the props cache.
  • A cached graph is published after its transaction commits.
  • IRedbObjectCache is the public interface of the props cache (Get, GetWithoutHashValidation, Set, FilterNeedToLoad, Remove, Clear, GetStats, RemoveObjectsOfTypes); the built-in implementation is MemoryRedbObjectCache.
  • PropsCacheStatistics: hit and miss statistics through GetStats().

List cache

  • EnableListCache (default true) caches lists and their items; ListCacheTtl (default 5 minutes, max 7 days).
  • Saving or deleting a list or an item through IListProvider invalidates it locally; other processes see the change after ListCacheTtl.

Metadata cache

  • EnableMetadataCache (default true) caches schemes and structures; MetadataCacheLifetimeMinutes (default 30).
  • WarmupMetadataCacheOnInit (default true): InitializeAsync loads all scheme metadata up front.

Isolation and unloading

  • Every cache is isolated per cache domain (see Cache domains and several databases): two databases in one process never share entries.
  • Collectible AssemblyLoadContext: when a context unloads, redb drops that module's objects from the props and list caches; caches keyed by type hold the types weakly; the host only calls Unload().

Configuration switches (RedbServiceConfiguration)

Save

  • MissingObjectStrategy.AutoSwitchToInsert (default): saving an object with an id that is not in the database inserts it.
  • MissingObjectStrategy.ThrowException: refuses such a save.
  • MissingObjectStrategy.ReturnNull: returns without an error.
  • ObjectIdResetStrategy (property IdResetStrategy) Manual (default): the id stays on the instance after a delete.
  • ObjectIdResetStrategy.AutoResetOnDelete: DeleteAsync(RedbObject) resets the instance id.
  • ObjectIdResetStrategy.AutoCreateNewOnSave: saving a deleted object creates a new one.
  • AutoSyncSchemesOnSave (default true): saving an unknown Props type syncs its scheme first.
  • AutoSetModifyDate (default true), AutoRecomputeHash (default true).
  • EnableDataValidation (default true), EnableSchemaValidation (default true).
  • BulkInsertTimeout (default null, the driver's value; TimeSpan.Zero means no limit): one COPY on PostgreSQL or one SqlBulkCopy on SQL Server within a save.
  • SystemUserId (default 0): the user of writes in the system context.
  • JsonOptions: WriteIndented (false), UseUnsafeRelaxedJsonEscaping (true).
  • PropsSaveStrategy: see Save, load, delete.

Load

  • DefaultLoadDepth (default 10, range 1 to 100): the depth of nested RedbObject references loaded eagerly.
  • DefaultMaxTreeDepth (default 50, range 1 to 1000): the tree depth limit.
  • ThrowOnObjectNotFound (default false): false returns null for one object and skips missing ids in a batch; true throws.
  • ThrowOnSchemeMismatch (default false): LoadAsync<T> of an object of another scheme returns null (a soft-deleted object reads as null); true throws RedbSchemeMismatchException.
  • PreloadListItemLinkedObjects: see Reference lists.
  • EnableLazyReferences, LazyReferenceAccess, LazyLoadWithoutScope: see Lazy loading.

Schema and start-up

  • DefaultStrictDeleteExtra (default true): scheme sync deletes structures the class no longer has.
  • DefaultDestructiveSyncAtEqualVersion (default false): lets the sync drop or retype a structure without a raised RedbScheme version.
  • EnsureCreated (default false): a hosted service creates the schema at start-up.
  • AutoApplyDatabaseUpgrades (default true): start-up applies the module and schema upgrades; false only checks and stops with RedbSchemaOutdatedException. SQLite ignores it.
  • SchemaLockTimeout (default 15 minutes): how long to wait for a schema lock held by another process; then RedbSchemaLockTimeoutException.
  • CheckBaseIndexesOnStart (default true): one warning naming missing or invalid indexes.
  • KeepSqlitePlannerStatistics (default true) and MaintenanceAnalysisLimit (default 1000): SQLite only.
  • EnablePvtPrefilter (default true, Pro only): the query planner; WithQueryPlanner(bool) switches it for a block of code.
  • StringCollation (default null) and CreateStringCollationIndex (default false); the index is built by the PostgreSQL Pro provider.

At run time

  • IRedbService.UpdateConfiguration(Action<RedbServiceConfiguration>) or (Action<RedbServiceConfigurationBuilder>) changes the configuration at run time.

Cache domains and several databases

  • CacheDomain names the cache partition of a service. The default is a 16-hex SHA-256 of the connection string with the password removed, or "default" without a connection string.
  • IRedbService.CacheDomain is the effective domain of a service; RedbServiceConfiguration.GetEffectiveCacheDomain() and the static ComputeCacheDomain(connectionString) compute it.
  • Set CacheDomain explicitly when two services reach the same database through different connection strings and must share caches.
  • The metadata, props, list and permission caches and the key generators are partitioned by domain, so several databases (and engines) in one process stay apart.
  • IRedbService.BeginAccess() makes the service the scope that lazy loads run on, for a block (UI event handlers, callbacks in another execution context).
  • A lazy load picks the nearest live service of its own database in the calling flow; an item of unknown origin is read only when every live service in the flow reads the same database.
  • Free registration: AddRedb(o => o.UsePostgres(...) | o.UseMsSql(...) | o.UseSqlite(...)); AddRedbPostgres, AddRedbPostgresFromConfig, AddRedbSqlite, AddRedbSqliteFromConfig, AddRedbService, AddValidatedRedbService, AddRedbServiceWithHotReload.
  • Pro registration: AddRedbPro(o => o.UsePostgres | UseMsSql | UseSqlite); AddRedbProPostgres, AddRedbProMSSql, AddRedbProSqlite with FromConfig and WithConfig forms; AddRedbPostgresPro, AddRedbMSSqlPro, AddRedbSqlitePro.
  • redb registers one IRedbService per service container (scoped); it has no keyed registration.
  • Named instances come from the hosts: in redb.Route context.RegisterRedbService(name, service), in redb.Tsak the "Redb" configuration sections.
  • IRedbConnection.LeaseAsync lends the connection of the service you resolved; a named service lends its own; inside a TransactionScope every scope of that database lends the scope's one connection.
  • Explicit transactions belong to the DI scope that began them: IRedbContext.BeginTransactionAsync(isolationLevel), ExecuteAtomicAsync(...) with or without an isolation level.

Transactions and the connection lease

redb works inside your transactions and lets your own SQL run in redb's.

  • redb.Context.BeginTransactionAsync(isolationLevel) opens an explicit transaction; ExecuteAtomicAsync runs a block atomically and joins a transaction that is already open.
  • The isolation level applies on PostgreSQL and SQL Server. SQLite accepts it and stays a single serial writer.
  • A System.Transactions TransactionScope is joined: every redb call to the same database inside it shares one connection, so the transaction does not become distributed. On SQLite the driver cannot enlist, so redb runs its own transaction on that connection.
  • IRedbConnection.LeaseAsync returns a RedbConnectionLease (Connection, Transaction, CreateCommand()), so your own SQL command runs in redb's transaction on redb's connection.
  • GetUnderlyingConnectionAsync hands the connection to code that owns it for a whole piece of work: EF Core, PostgreSQL COPY, SqlBulkCopy.
  • Deadlocks: redb retries the units it owns outside a transaction; DeadlockRetryHelper.ExecuteWithRetryAsync retries your own unit.

Uniqueness

[RedbUnique] on a property makes its value a unique key within the scheme, enforced by a database index.

  • A duplicate raises RedbUniqueViolationException.
  • Allowed on scalars; on nested classes, arrays and dictionaries, where the whole content is the key; and on collections with UniqueScope.Scheme (every element unique across the scheme) or UniqueScope.Collection (no duplicates within one object).
  • null never takes part; strings compare exactly after Unicode NFC normalisation.
  • GetByUniqueAsync<TProps> finds an object by its key; SaveByUniqueAsync<TProps> inserts or updates by key.
  • Adding [RedbUnique] to a scheme that already has data recomputes the keys at the next sync and reports duplicates instead of failing start-up; RecomputeUniqueAsync<TProps> runs the recompute on demand.

Migrations

  • Property renames, type changes and dropped properties are handled at scheme sync (see Storage model and schemes).
  • Data migrations of Props classes are Pro only: IRedbMigration<TProps>, run with MigrateAsync<TProps, TMigration>.

Export, import and the command line

  • redb.Export writes and reads .redb files (JSONL in ZIP): ExportService.ExportAsync, ImportService.ImportAsync.
  • An export from one database engine imports into another: PostgreSQL, SQL Server, SQLite.
  • The redb command line tool (package redb.CLI):
    • init creates the redb schema in an existing database;
    • schema writes the schema SQL script;
    • export and import work with .redb files; restart the applications that use the target database after an import;
    • indexes check and indexes repair compare the base indexes with the build and build the missing ones: CONCURRENTLY on PostgreSQL, ONLINE on SQL Server where the edition supports it, plainly on SQLite;
    • flat unfolds redb objects into ordinary relational tables and copies the data (--ddl-only, --dry-run).

Users, roles, permissions, maintenance

  • UserProvider, RoleProvider and permission checks are built in; SetCurrentUser sets the acting user, and CreateSystemContext runs code as the system.
  • IRedbService.Maintenance: AnalyzeAsync, GetTableStatsAsync, GetIndexStatsAsync.

Packages, editions and platforms

  • Free packages: redb.Postgres, redb.MSSql, redb.SQLite (Apache 2.0). Pro packages: redb.Postgres.Pro, redb.MSSql.Pro, redb.SQLite.Pro; they bring redb.Core.Pro.
  • Free and Pro take the same LINQ API and differ in the engine. Pro adds the query planner, ChangeTracking saves, data migrations and SQLite in pure C#.
  • redb.SQLite.Pro needs no native extension, so it runs in Blazor WebAssembly and on mobile. Free SQLite (redb.SQLite) uses a native loadable extension.
  • Supported databases: PostgreSQL 15+, Microsoft SQL Server 2019+, SQLite.
  • Supported .NET: .NET 10 and .NET 11.
  • dotnet new project templates ship in redb.Templates.

Sources and documentation: github.com/redbase-app/redb, redbase.app.