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.MigrateStructureTypeAsyncchanges the stored type of a property.DropUnknownStructuresAsync<TProps>removes stored properties the class no longer has.GetSchemeByTypeAsync,GetSchemesAsyncandGetStructureTreeAsyncread scheme metadata.EnsureDatabaseAsynccreates the redb schema;GetSchemaScriptandGetUpgradeScriptreturn the SQL for running it by hand.CheckSchemaAsyncand theSchemaProblemsproperty report a schema that does not match the build.CheckBaseIndexesAsyncreports missing or invalid base indexes;RepairBaseIndexesAsyncbuilds 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-
Nullablevalue 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),TimeOnlyandTimeSpan(stored as ticks).- Nullable forms of all value types (
int?,DateTime?,Guid?and so on). enumandenum?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 raisesRedbValueStringTooLongException.
Nested classes
- A class of your own (not in a
Systemnamespace) 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>andIDictionary<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 otherValueTupleshapes. - 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 ofRedbObject<T>, and dictionaries withRedbObject<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
RedbListItemproperty, 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),GroupByArrayby 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,GroupBykeys): the collection folded in index order.
Save, load, delete
One call saves or loads a whole object with its Props.
SaveAsyncsaves one object or many;LoadAsync<TProps>loads by id;LoadJsonAsyncreturns the stored object as JSON.AddNewObjectsAsyncinserts new objects in bulk (see Batch operations).DeleteAsyncdeletes for good;SoftDeleteAsyncmoves objects to the trash;PurgeTrashAsyncandDeleteWithPurgeAsyncempty it.GetDeletionProgressAsyncfollows a long purge.LockForUpdateAsyncandLockForUpdateRequiredAsynclock objects for update inside a transaction.LoadWithParentsAsync<TProps>loads an object with its chain of parents.IRedbSaveInterceptorruns 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 withNotSupportedException.
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 whereid == 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
SqlBulkCopyabove that; on SQLite a chunked multi-row INSERT in one transaction. BulkInsertTimeout: the time limit of one COPY orSqlBulkCopy.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)andDeleteAsync(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; returnsDeletionMark(TrashId, MarkedCount).PurgeTrashAsync(trashId, totalCount, batchSize = 10, progress)andDeleteWithPurgeAsync(ids, batchSize = 10, progress, trashParentId): physical delete in portions, with progress.GetDeletionProgressAsync(trashId)andGetUserActiveDeletionsAsync(userId)returnPurgeProgress(TrashId, Deleted, Remaining, Status, StartedAt, UserId).IBackgroundDeletionService.DeleteAsync: soft delete now, purge later by a polling worker.GetOrphanedDeletionTasksAsyncandTryClaimOrphanedTaskAsyncmake the background purge safe across cluster nodes.LockForUpdateAsync(ids)andLockForUpdateRequiredAsync(ids): row locks on many objects inside a transaction.ListProvider.AddItemsAsyncandSaveListWithItemsAsync: many list items in one call.- There is no bulk update by query: changes go through
SaveAsyncof loaded objects.
Lazy loading
LoadAsync<T>(id, depth = 10)andLoadAsync(ids, depth): references to other objects are loaded eagerly down todepth.WithPropsDepth(depth)on a query: the depth of nestedRedbObjectloading 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 declaredvirtual(RedbObject<T>or a collection of them) come back as stubs at any depth;virtualon 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 aSynchronizationContext.LazyReferenceAccess.Throw: the getter throwsRedbSynchronousLazyLoadException; meant for Blazor WebAssembly and UI hosts.RedbObject<T>.LoadPropsAsync()andIsPropsLoaded: 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) throwsRedbLazyLoadScopeEndedException;FreshScopeopens 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 raisesRedbUnloadedReferenceExceptioninstead 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>()andQuery<T>(user).TreeQuery<T>()andTreeQuery<T>(rootId | root | rootIds | roots, maxDepth), each with a user overload.
Filter
Where(p => ...); chainedWherecalls combine with AND.WhereRedb(o => ...)filters on base fields.WhereIn(selector, values)andWhereInRedb(selector, values)translate to SQL IN.- Base fields for the
*Redbmethods: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.HasValueand.Value.- SQL null semantics: a field without a value matches neither
==nor!=. - Arithmetic
+ - * / %between fields and constants; unary minus. - Conditional
c ? a : band coalescea ?? b. Math.Abs,Round(with digits),Floor,Ceiling,Truncate,Sqrt,Sign,Exp,Log,Log(x, base),Log10,Pow.- String
Contains,StartsWith,EndsWith, each withStringComparison; 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])andRegex.Replace(input, pattern, replacement): PostgreSQL~/~*, SQLite built-in functions; on SQL Server they need SQL Server 2025 (compatibility level 170).DateTimeandDateTimeOffsetmembersYear,Month,Day,Hour,Minute,Second,DayOfWeek,DayOfYear.DateTimeandDateTimeOffsetAddDays,AddMonths,AddYears,AddHours,AddMinutes,AddSeconds.DateOnly,TimeOnly,TimeSpan: comparison and ranges.Guid, enum (compared by name),booland their nullable forms.Containson 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/Lengthcompared with a number. Any(predicate)over an array of classes (Pro only): every condition reads the same element; comparisons, null checks,Containsof a list,&&,||,!. The Free providers refuse it.- An element by index
arr[i]andarr[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, andStatus == 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. StringCollationnames 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;*Redbforms for base fields.- Order keys: field paths, arithmetic of fields, unary minus, string functions (
ToLower,ToUpper,Trimand others), list itemValue/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)andDistinctByRedb(key): one object per key.- In Pro,
DistinctBycombines withOrderBy(key first),Skip/Take, andCountAsynccounting the keys.
Results and existence
ToListAsync,FirstOrDefaultAsync(),FirstOrDefaultAsync(predicate),CountAsync,AnyAsync(),AnyAsync(predicate),AllAsync(predicate).
Projection
Select(x => new { ... })overRedbObject<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,MaxAsyncwith a selector over Props.SumRedbAsync,AverageRedbAsync,MinRedbAsync,MaxRedbAsyncover base fields.GetStatisticsAsync(selector): Sum, Average, Min, Max and Count in one query.AggregateAsync(x => new { ... })andAggregateRedbAsync: several aggregates in one query withAgg.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)andGroupByRedb(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, orSelectManyover 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
NotSupportedExceptionin 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(); boundsPreceding(n),UnboundedPreceding,CurrentRow,Following(n),UnboundedFollowing. Wherebefore a window.Skip/Takewith a window (Pro only): the window is computed over the whole filtered set, and the page is returned.GroupBy(...).WithWindow(...)andGroupByArray(...).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.GroupByandWithWindowinside a subtree.AnyAsyncon 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, andToSqlStringAsync(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 indexerlist["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
RedbObjectof any scheme (IdObject/Object, an untypedIRedbObject) 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 leavesObjectlazy.RedbListItem.Objectread lazily outside a live scope followsLazyLoadWithoutScope;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)andAddItemsAsync(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);WhereInonValue. Anyover an item array:Value/Alias/Idwith==only, other operators are refused;!Anyincludes empty and missing arrays.- Sort by
Status.ValueorStatus.Alias. GroupByby an item (the key is filled with the item:Id,Value,Alias) or by itsValue/Alias.GroupByArrayover item arrays is refused.- SQL Server, Free only: a negated comparison of an item's
Id/Value/Aliasalso 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 wholeRedbObject<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
Hashand 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 orTransactionScope) 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.
IRedbObjectCacheis the public interface of the props cache (Get,GetWithoutHashValidation,Set,FilterNeedToLoad,Remove,Clear,GetStats,RemoveObjectsOfTypes); the built-in implementation isMemoryRedbObjectCache.PropsCacheStatistics: hit and miss statistics throughGetStats().
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
IListProviderinvalidates it locally; other processes see the change afterListCacheTtl.
Metadata cache
EnableMetadataCache(default true) caches schemes and structures;MetadataCacheLifetimeMinutes(default 30).WarmupMetadataCacheOnInit(default true):InitializeAsyncloads 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 callsUnload().
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(propertyIdResetStrategy)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.Zeromeans no limit): one COPY on PostgreSQL or oneSqlBulkCopyon 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 nestedRedbObjectreferences 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 throwsRedbSchemeMismatchException.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 raisedRedbSchemeversion.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 withRedbSchemaOutdatedException. SQLite ignores it.SchemaLockTimeout(default 15 minutes): how long to wait for a schema lock held by another process; thenRedbSchemaLockTimeoutException.CheckBaseIndexesOnStart(default true): one warning naming missing or invalid indexes.KeepSqlitePlannerStatistics(default true) andMaintenanceAnalysisLimit(default 1000): SQLite only.EnablePvtPrefilter(default true, Pro only): the query planner;WithQueryPlanner(bool)switches it for a block of code.StringCollation(default null) andCreateStringCollationIndex(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
CacheDomainnames 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.CacheDomainis the effective domain of a service;RedbServiceConfiguration.GetEffectiveCacheDomain()and the staticComputeCacheDomain(connectionString)compute it.- Set
CacheDomainexplicitly 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,AddRedbProSqlitewithFromConfigandWithConfigforms;AddRedbPostgresPro,AddRedbMSSqlPro,AddRedbSqlitePro. - redb registers one
IRedbServiceper 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.LeaseAsynclends the connection of the service you resolved; a named service lends its own; inside aTransactionScopeevery 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;ExecuteAtomicAsyncruns 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.TransactionsTransactionScopeis 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.LeaseAsyncreturns aRedbConnectionLease(Connection,Transaction,CreateCommand()), so your own SQL command runs in redb's transaction on redb's connection.GetUnderlyingConnectionAsynchands 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.ExecuteWithRetryAsyncretries 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) orUniqueScope.Collection(no duplicates within one object). nullnever 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 withMigrateAsync<TProps, TMigration>.
Export, import and the command line
redb.Exportwrites and reads.redbfiles (JSONL in ZIP):ExportService.ExportAsync,ImportService.ImportAsync.- An export from one database engine imports into another: PostgreSQL, SQL Server, SQLite.
- The
redbcommand line tool (packageredb.CLI):initcreates the redb schema in an existing database;schemawrites the schema SQL script;exportandimportwork with.redbfiles; restart the applications that use the target database after an import;indexes checkandindexes repaircompare 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;flatunfolds redb objects into ordinary relational tables and copies the data (--ddl-only,--dry-run).
Users, roles, permissions, maintenance
UserProvider,RoleProviderand permission checks are built in;SetCurrentUsersets the acting user, andCreateSystemContextruns 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 bringredb.Core.Pro. - Free and Pro take the same LINQ API and differ in the engine. Pro adds the query planner,
ChangeTrackingsaves, data migrations and SQLite in pure C#. redb.SQLite.Proneeds 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 newproject templates ship inredb.Templates.
Sources and documentation: github.com/redbase-app/redb, redbase.app.