Code Examples

Learn RedBase by example. Browse working code samples for LINQ queries, bulk operations, tree structures, and more.

Data Model - EmployeeProps Click to view data model used in all examples
Tag with priority for categorization.
/// <summary>
/// Tag with priority for categorization.
/// </summary>
public class Tag
{
    public string Name { get; set; } = string.Empty;
    public int Priority { get; set; }
    public string? Description { get; set; }
}

/// <summary>
/// Project metrics for analytics.
/// </summary>
[RedbScheme("ProjectMetrics")]
public class ProjectMetricsProps
{
    public long ProjectId { get; set; }
    public long? TasksCompleted { get; set; }
    public long? TasksTotal { get; set; }
    public long? BugsFixed { get; set; }
    public double? Budget { get; set; }
    public long? TeamSize { get; set; }
    public Tag[]? Tags { get; set; }
    public string[]? Technologies { get; set; }
}

/// <summary>
/// Address with city, street and building details.
/// </summary>
public class Address
{
    public string City { get; set; } = string.Empty;
    public string Street { get; set; } = string.Empty;
    public BuildingInfo? Building { get; set; }
}

/// <summary>
/// Building information with floor and amenities.
/// </summary>
public class BuildingInfo
{
    public int Floor { get; set; }
    public string Name { get; set; } = string.Empty;
    public string[]? Amenities { get; set; }
    public int[]? AccessCodes { get; set; }
    public string[]? ParkingSpots { get; set; }
    public int[]? ElevatorFloors { get; set; }
}

/// <summary>
/// Contact detail key-value pair.
/// </summary>
public class ContactDetail
{
    public string Label { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
}

/// <summary>
/// Contact information (email, phone, etc).
/// </summary>
public class Contact
{
    public string Type { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
    public bool IsVerified { get; set; }
    public int[]? NotificationHours { get; set; }
    public ContactDetail[]? Metadata { get; set; }
}

/// <summary>
/// Department info with tags, metrics and nested budget data.
/// </summary>
public class Department
{
    public string Name { get; set; } = string.Empty;
    public int HeadCount { get; set; }
    public string[] Projects { get; set; } = [];
    public Tag[] Leaders { get; set; } = [];
    public Dictionary<string, int>? BudgetByYear { get; set; }
}

/// <summary>
/// Employee props - main model for examples.
/// Demonstrates all supported types:
/// - Simple types (int, string, DateTime, long, decimal)
/// - Arrays (string[], int[])
/// - Business classes (Address with nested BuildingInfo)
/// - Array of business classes (Contact[])
/// - RedbObject references (CurrentProject, PastProjects[])
/// - Dictionary types (various key and value types)
/// </summary>
[RedbScheme("Employee")]
public class EmployeeProps
{
    // Basic info
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public int Age { get; set; }
    public DateTime HireDate { get; set; }
    public string Position { get; set; } = string.Empty;
    public decimal Salary { get; set; }
    public string Department { get; set; } = string.Empty;
    public string? EmployeeCode { get; set; }

    // Skills and certifications (arrays)
    public string[]? Skills { get; set; }
    public int[]? SkillLevels { get; set; }
    public string[]? Certifications { get; set; }
    public int[]? CertificationYears { get; set; }

    // Addresses (business classes)
    public Address? HomeAddress { get; set; }
    public Address? WorkAddress { get; set; }
    public Address? EmergencyAddress { get; set; }

    // Contacts (array of business classes)
    public Contact[]? Contacts { get; set; }

    // Project references (RedbObject)
    public RedbObject<ProjectMetricsProps>? CurrentProject { get; set; }
    public RedbObject<ProjectMetricsProps>[]? PastProjects { get; set; }

    // Phone directory: extension -> phone number
    public Dictionary<string, string>? PhoneDirectory { get; set; }

    // Office locations by city
    public Dictionary<string, Address>? OfficeLocations { get; set; }

    // Bonus history by year
    public Dictionary<int, decimal>? BonusByYear { get; set; }

    // Department details with complex nested data (Pro)
    public Dictionary<string, Department>? DepartmentHistory { get; set; }

    // Composite key: (year, quarter) -> performance score (Pro)
    public Dictionary<(int Year, string Quarter), string>? PerformanceReviews { get; set; }

    // Project metrics by code (Pro)
    public Dictionary<string, RedbObject<ProjectMetricsProps>>? ProjectMetrics { get; set; }
}

/// <summary>
/// Department props for tree examples (corporate hierarchy).
/// Used with TreeRedbObject for organizational structure.
/// Similar to CategoryTestProps in ConsoleTest.
/// </summary>
[RedbScheme("Department")]
public class DepartmentProps
{
    /// <summary>Department name (e.g. "IT Department Moscow").</summary>
    public string Name { get; set; } = string.Empty;

    /// <summary>Description (e.g. "Software development team").</summary>
    public string Description { get; set; } = string.Empty;

    /// <summary>Is department active?</summary>
    public bool IsActive { get; set; } = true;

    /// <summary>Budget in USD.</summary>
    public decimal Budget { get; set; }

    /// <summary>Department code (e.g. "IT-MSK-DEV").</summary>
    public string Code { get; set; } = string.Empty;
}

/// <summary>
/// City props for list examples (linked objects).
/// Used as target object for RedbListItem.Object reference.
/// </summary>
[RedbScheme("City")]
public class CityProps
{
    /// <summary>City name.</summary>
    public string Name { get; set; } = string.Empty;
    
    /// <summary>Population count.</summary>
    public int Population { get; set; }
    
    /// <summary>Region or district.</summary>
    public string Region { get; set; } = string.Empty;
    
    /// <summary>Is capital city?</summary>
    public bool IsCapital { get; set; }
    
    /// <summary>GPS coordinates [lat, lon].</summary>
    public double[] Coordinates { get; set; } = [];
}

/// <summary>
/// Person props demonstrating ListItem fields.
/// Shows single ListItem and List of ListItems usage.
/// </summary>
[RedbScheme("Person")]
public class PersonProps
{
    /// <summary>Person name.</summary>
    public string Name { get; set; } = string.Empty;
    
    /// <summary>Age in years.</summary>
    public int Age { get; set; }
    
    /// <summary>Email address.</summary>
    public string Email { get; set; } = string.Empty;
    
    /// <summary>Single ListItem field (e.g. status from dictionary).</summary>
    public RedbListItem? Status { get; set; }
    
    /// <summary>Array of ListItems (e.g. roles from dictionary).</summary>
    public List<RedbListItem>? Roles { get; set; }
}

/// <summary>
/// Product with a unique business key (V4 [RedbUnique]): the SKU is unique per scheme,
/// enforced by the database over the hash of the canonical value. Used by E003.
/// </summary>
public class ProductProps
{
    /// <summary>Unique business key. NULL never participates in uniqueness.</summary>
    [RedbUnique]
    public string? Sku { get; set; }

    /// <summary>Display name (not unique).</summary>
    public string Title { get; set; } = string.Empty;

    /// <summary>Price in USD.</summary>
    public decimal Price { get; set; }
}

Tree Create Sequential - ANTIPATTERN (slow by design)

Sequential create tree hierarchy - deliberate ANTIPATTERN demo.
This example is SLOW BY DESIGN: it saves ~100 tree nodes one CreateChildAsync at a time,
paying a full save pipeline (key allocation, hash, values insert, commit) per node, to give
E088 (bulk AddNewObjectsAsync, one round-trip for the whole level) a baseline to beat.
Do NOT copy this shape into application code - use the bulk API of E088.
Structure:
  • 1 root (TechCorp)
  • 10 regional offices
  • 50 departments (5 per office)
  • 40 teams (4 per first 10 departments)
await redb.SyncSchemeAsync<DepartmentProps>();
// Run E087 first to cleanup existing data

// Measure sequential creation
var sw = Stopwatch.StartNew();
var count = await CreateTreeSequentially(redb);
sw.Stop();

var rate = count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1);

Console.WriteLine($"[E089] ANTIPATTERN demo: {count} nodes saved one round-trip each on purpose - compare with E088 (bulk).");
CreateTreeSequentially
private static async Task<int> CreateTreeSequentially(IRedbService redb)
{
    var count = 0;

    // Level 0: Root
    var root = CreateDept("TechCorp", "CORP", "Headquarters", 50_000_000m);
    root.id = await redb.SaveAsync(root);
    count++;

    // Level 1: Regional offices
    var offices = new TreeRedbObject<DepartmentProps>[OfficeCount];
    for (int i = 0; i < OfficeCount; i++)
    {
        var city = Cities[i % Cities.Length];
        offices[i] = CreateDept($"{city} Office", $"OFF-{i + 1:D2}", $"Regional office {city}", 5_000_000m - i * 200_000m);
        offices[i].id = await redb.CreateChildAsync(offices[i], root);
        count++;
    }

    // Level 2: Departments in each office
    var depts = new List<TreeRedbObject<DepartmentProps>>();
    for (int o = 0; o < OfficeCount; o++)
    {
        for (int d = 0; d < DeptPerOffice; d++)
        {
            var deptName = Departments[d % Departments.Length];
            var dept = CreateDept($"{deptName} {o + 1}-{d + 1}", $"DEPT-{o + 1:D2}-{d + 1:D2}", deptName, 1_000_000m - d * 100_000m);
            dept.id = await redb.CreateChildAsync(dept, offices[o]);
            depts.Add(dept);
            count++;
        }
    }

    // Level 3: Teams in first 10 departments
    for (int d = 0; d < TeamsForFirstDepts && d < depts.Count; d++)
    {
        for (int t = 0; t < TeamsPerDept; t++)
        {
            var teamName = Teams[t % Teams.Length];
            var team = CreateDept($"{teamName} Team {d + 1}-{t + 1}", $"TEAM-{d + 1:D2}-{t + 1:D2}", teamName, 300_000m - t * 50_000m);
            await redb.CreateChildAsync(team, depts[d]);
            count++;
        }
    }

    return count;
}
TreeCreateChildAsyncSequentialAntipatternPro
PG Pro 6096ms(101)
postgres.ef 1997ms(101)
postgres.pro.repeat 5984ms(101)
postgres.pro.cache 5884ms(101)
postgres.ef.repeat 2000ms(101)
MS Pro 11775ms(101)
mssql.pro.repeat 11337ms(101)
mssql.pro.cache 11034ms(101)
sqlite.pro 276ms(101)
sqlite.pro.repeat 248ms(101)
sqlite.pro.cache 341ms(101)

Tree Load - Full Hierarchy

Load full tree with LoadTreeAsync.
Requires E089 to run first (creates tree data).
Loads entire hierarchy from root with specified depth.
// Find root
var roots = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code == "CORP")
    .Take(1)
    .ToListAsync();

if (roots.Count == 0)
    return Fail("E090", "Tree Load - Full Hierarchy", ExampleTier.Free, 0, "No tree. Run E089 first.");

var root = (TreeRedbObject<DepartmentProps>)roots[0];

// Measure LoadTreeAsync
var sw = Stopwatch.StartNew();
var tree = await redb.LoadTreeAsync<DepartmentProps>(root, maxDepth: 5);
sw.Stop();

var nodeCount = CountNodes(tree);
CountNodes
private static int CountNodes(ITreeRedbObject<DepartmentProps> node)
{
    var count = 1;
    foreach (var child in node.Children.OfType<ITreeRedbObject<DepartmentProps>>())
        count += CountNodes(child);
    return count;
}
TreeLoadTreeAsyncHierarchyProIRedbService.LoadTreeAsyncTreeRedbObject
PG Pro 93ms(101)
postgres.pro.repeat 56ms(101)
postgres.pro.cache 52ms(101)
MS Pro 95ms(101)
mssql.pro.repeat 107ms(101)
mssql.pro.cache 87ms(101)
sqlite.pro 13ms(101)
sqlite.pro.repeat 12ms(101)
sqlite.pro.cache 9ms(101)

Tree Count - CountAsync

Count tree nodes with TreeQuery.
Requires E089 to run first (creates tree data).
CountAsync on TreeQuery - counts all nodes in tree.
var sw = Stopwatch.StartNew();
var count = await redb.TreeQuery<DepartmentProps>().CountAsync();
sw.Stop();

if (count == 0)
    return Fail("E091", "Tree Count - CountAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree. Run E089 first.");
TreeTreeQueryCountAsyncPro
PG Pro 14ms(202)
postgres.ef 12ms(202)
postgres.pro.repeat 7ms(202)
postgres.pro.cache 7ms(202)
postgres.ef.repeat 9ms(202)
MS Pro 20ms(202)
mssql.pro.repeat 18ms(202)
mssql.pro.cache 18ms(202)
sqlite.pro 10ms(202)
sqlite.pro.repeat 0ms(202)
sqlite.pro.cache 0ms(202)

Tree Children - Direct

Get direct children of a node.
Uses GetChildrenAsync - returns only immediate children, not descendants.
var sw = Stopwatch.StartNew();

// Find TechCorp root - use TreeQuery for tree objects!
var roots = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code == "CORP")
    .Take(1)
    .ToListAsync();

if (roots.Count == 0)
{
    return Ok("E092", "Tree Children - Direct", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["No tree found. Run E090 first."]);
}

var root = (TreeRedbObject<DepartmentProps>)roots[0];

// Get direct children only
var children = await redb.GetChildrenAsync<DepartmentProps>(root);
var childList = children.ToList();
sw.Stop();

var names = childList.Select(c => c.Name).ToArray();
TreeGetChildrenAsyncPro
PG Pro 62ms(10)
postgres.ef 34ms(10)
postgres.pro.repeat 15ms(10)
postgres.pro.cache 18ms(10)
postgres.ef.repeat 32ms(10)
MS Pro 64ms(10)
mssql.pro.repeat 25ms(10)
mssql.pro.cache 35ms(10)
sqlite.pro 5ms(10)
sqlite.pro.repeat 1ms(10)
sqlite.pro.cache 2ms(10)

Tree Path - Breadcrumbs

Get path from node to root.
Builds breadcrumbs: Team > Department > Office > TechCorp.
var sw = Stopwatch.StartNew();

// Find deepest node (any team at level 3) - use TreeQuery!
var nodes = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code.StartsWith("TEAM-"))
    .Take(1)
    .ToListAsync();

if (nodes.Count == 0)
{
    return Ok("E093", "Tree Path - Breadcrumbs", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["No tree found. Run E088 or E089 first."]);
}

var node = (TreeRedbObject<DepartmentProps>)nodes[0];

// Get path to root (returns: DevAlpha, IT-MSK, Moscow, TechCorp)
var path = await redb.GetPathToRootAsync<DepartmentProps>(node);
var pathList = path.ToList();
sw.Stop();

var breadcrumbs = string.Join(" > ", pathList.Select(n => n.Name));
TreeGetPathToRootAsyncBreadcrumbsPro
PG Pro 79ms(4)
postgres.pro.repeat 37ms(4)
postgres.pro.cache 40ms(4)
MS Pro 73ms(4)
mssql.pro.repeat 33ms(4)
mssql.pro.cache 35ms(4)
sqlite.pro 5ms(4)
sqlite.pro.repeat 1ms(4)
sqlite.pro.cache 1ms(4)

Tree Descendants - All

Get all descendants of a node.
Returns all children, grandchildren, etc. recursively.
var sw = Stopwatch.StartNew();

// Find TechCorp root - use TreeQuery!
var roots = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code == "CORP")
    .Take(1)
    .ToListAsync();

if (roots.Count == 0)
{
    return Ok("E094", "Tree Descendants - All", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["No tree found. Run E090 first."]);
}

var root = (TreeRedbObject<DepartmentProps>)roots[0];

// Get ALL descendants (children, grandchildren, etc.)
var descendants = await redb.GetDescendantsAsync<DepartmentProps>(root);
var list = descendants.ToList();
sw.Stop();

// Group by level
var byLevel = list.GroupBy(d => d.Level).OrderBy(g => g.Key).ToList();
var output = byLevel.Select(g => $"Level {g.Key}: {string.Join(", ", g.Select(d => d.Props.Code))}").ToList();
output.Insert(0, $"Root: {root.Name}, Total descendants: {list.Count}");
TreeGetDescendantsAsyncRecursivePro
PG Pro 75ms(100)
postgres.pro.repeat 27ms(100)
postgres.pro.cache 26ms(100)
MS Pro 75ms(100)
mssql.pro.repeat 31ms(100)
mssql.pro.cache 32ms(100)
sqlite.pro 5ms(100)
sqlite.pro.repeat 2ms(100)
sqlite.pro.cache 2ms(100)

Tree Move - Relocate Node

Move node to new parent.
Demonstrates MoveObjectAsync - moves entire subtree.
var sw = Stopwatch.StartNew();

// Find a department to move - use TreeQuery!
var nodes = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code.StartsWith("DEPT-01-"))
    .Take(1)
    .ToListAsync();

if (nodes.Count == 0)
{
    return Ok("E095", "Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["No tree found. Run E088 or E089 first."]);
}

// Find another office as new parent - use TreeQuery!
var officeNodes = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Code == "OFF-02")
    .Take(1)
    .ToListAsync();

if (officeNodes.Count == 0)
{
    return Ok("E095", "Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["Target office not found."]);
}

var dept = (TreeRedbObject<DepartmentProps>)nodes[0];
var targetOffice = (TreeRedbObject<DepartmentProps>)officeNodes[0];
var originalParentId = dept.parent_id;

// Move department to another office
await redb.MoveObjectAsync(dept, targetOffice);

// Move back to original parent
if (originalParentId.HasValue)
{
    var originalParent = await redb.TreeQuery<DepartmentProps>()
        .Where(d => d.Code == "OFF-01")
        .Take(1)
        .ToListAsync();

    if (originalParent.Count > 0)
    {
        var origOffice = (TreeRedbObject<DepartmentProps>)originalParent[0];
        await redb.MoveObjectAsync(dept, origOffice);
    }
}

sw.Stop();
TreeMoveObjectAsyncPro
PG Pro 139ms(1)
postgres.ef 65ms(1)
postgres.pro.repeat 74ms(1)
postgres.pro.cache 71ms(1)
postgres.ef.repeat 61ms(1)
MS Pro 151ms(1)
mssql.pro.repeat 93ms(1)
mssql.pro.cache 99ms(1)
sqlite.pro 5ms(1)
sqlite.pro.repeat 3ms(1)
sqlite.pro.cache 3ms(1)

Tree Query - LINQ on Trees

LINQ queries on tree structures.
TreeQuery combines tree traversal with Where/OrderBy/Take.
var sw = Stopwatch.StartNew();

// TreeQuery: find all IT departments
var itDepts = await redb.TreeQuery<DepartmentProps>()
    .Where(d => d.Name.Contains("IT"))
    .OrderBy(d => d.Name)
    .ToListAsync();

// var sql = await redb.TreeQuery<DepartmentProps>()
    // .Where(d => d.Name.Contains("IT"))
    // .ToSqlStringAsync();
// Console.WriteLine(sql);

sw.Stop();

var names = itDepts.Select(d => $"{d.Name} ({d.Props.Code})").ToArray();
TreeTreeQueryWhereOrderByPro
PG Pro 67ms(20)
postgres.ef 15ms(20)
postgres.pro.repeat 54ms(20)
postgres.pro.cache 59ms(20)
postgres.ef.repeat 19ms(20)
MS Pro 42ms(20)
mssql.pro.repeat 41ms(20)
mssql.pro.cache 43ms(20)
sqlite.pro 2ms(20)
sqlite.pro.repeat 1ms(20)
sqlite.pro.cache 1ms(20)

Tree Query - Roots Only

Find root nodes in tree.
WhereRoots returns only top-level nodes (parent_id = null).
var sw = Stopwatch.StartNew();

// Find all root nodes
var roots = await redb.TreeQuery<DepartmentProps>()
    .WhereRoots()
    .ToListAsync();

sw.Stop();

var names = roots.Select(r => $"{r.Name} ({r.Props.Code})").ToArray();
TreeTreeQueryWhereRootsProITreeQueryable.WhereRootsIRedbService.TreeQuery
PG Pro 36ms(2)
postgres.ef 18ms(2)
postgres.pro.repeat 6ms(2)
postgres.pro.cache 6ms(2)
postgres.ef.repeat 15ms(2)
MS Pro 31ms(2)
mssql.pro.repeat 15ms(2)
mssql.pro.cache 15ms(2)
sqlite.pro 1ms(2)
sqlite.pro.repeat 0ms(2)
sqlite.pro.cache 0ms(2)

Tree Query - Leaves Only

Find leaf nodes in tree.
WhereLeaves returns nodes with no children.
var sw = Stopwatch.StartNew();

// Find all leaf nodes (no children)
var leaves = await redb.TreeQuery<DepartmentProps>()
    .WhereLeaves()
    .ToListAsync();

sw.Stop();

var names = leaves.Select(l => $"{l.Name} ({l.Props.Code})").ToArray();
TreeTreeQueryWhereLeavesPro
PG Pro 43ms(160)
postgres.ef 18ms(160)
postgres.pro.repeat 9ms(160)
postgres.pro.cache 9ms(160)
postgres.ef.repeat 19ms(160)
MS Pro 38ms(160)
mssql.pro.repeat 24ms(160)
mssql.pro.cache 24ms(160)
sqlite.pro 4ms(160)
sqlite.pro.repeat 2ms(160)
sqlite.pro.cache 2ms(160)