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; }
}

Mixed Batch - Generic and Non-Generic

Demonstrates mixed batch save with both non-generic RedbObject and generic RedbObject<T> with Props=null.
Shows flexibility of REDB to handle different object types in single batch operation.
var sw = Stopwatch.StartNew();

var batchId = DateTime.UtcNow.Ticks;
var objects = new List<IRedbObject>();

// Add non-generic objects
objects.Add(new RedbObject
{
    name = $"Mixed_NonGeneric_1_{batchId}",
    value_string = "NonGeneric",
    value_long = 1
});

objects.Add(new RedbObject
{
    name = $"Mixed_NonGeneric_2_{batchId}",
    value_string = "NonGeneric",
    value_long = 2
});

// Add generic objects with Props=null
var scheme = await redb.EnsureSchemeFromTypeAsync<EmployeeProps>();

var gen1 = new RedbObject<EmployeeProps>
{
    name = $"Mixed_Generic_1_{batchId}",
    scheme_id = scheme.Id,
    value_string = "Generic",
    value_long = 3
};
gen1.Props = null!;
objects.Add(gen1);

var gen2 = new RedbObject<EmployeeProps>
{
    name = $"Mixed_Generic_2_{batchId}",
    scheme_id = scheme.Id,
    value_string = "Generic",
    value_long = 4
};
gen2.Props = null!;
objects.Add(gen2);

// Batch save mixed types
var ids = await redb.SaveAsync(objects);

// Batch load
var loaded = await redb.LoadAsync(ids);

sw.Stop();

if (loaded.Count != 4)
{
MixedBatchNonGenericGenericRedbObjectRedbObject<TProps>IRedbService.SaveAsync
PG Pro 71ms(4)
postgres.ef 20ms(4)
postgres.pro.repeat 70ms(4)
postgres.pro.cache 69ms(4)
postgres.ef.repeat 18ms(4)
MS Pro 104ms(4)
mssql.pro.repeat 129ms(4)
mssql.pro.cache 97ms(4)
sqlite.pro 1ms(4)
sqlite.pro.repeat 2ms(4)
sqlite.pro.cache 12ms(4)

Array - Contains

Demonstrates filtering by array element using Contains().
Server-side: = ANY(pvt."Skills") in PostgreSQL, STRING_SPLIT in MSSQL.
Pro feature: array operations in PVT.
var sw = Stopwatch.StartNew();

// Find employees who have "C#" skill
var query = redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && e.Skills.Contains("C#"))
    .Take(100);

// Uncomment to see generated SQL (contains ANY or STRING_SPLIT):
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine(sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && e.Skills.Contains("C#"))
    .CountAsync();

sw.Stop();

var skillSamples = results.Take(3)
    .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills?.Take(3) ?? [])}]");
ArrayContainsFilterIRedbQueryable.WhereArray.Contains
PG Pro 144ms(20064)
postgres.ef 1023ms(20063)
postgres.pro.repeat 115ms(20065)
postgres.pro.cache 115ms(20066)
postgres.ef.repeat 1031ms(20064)
MS Pro 323ms(20044)
mssql.pro.repeat 696ms(20045)
mssql.pro.cache 318ms(20046)
sqlite.pro 245ms(20021)
sqlite.pro.repeat 324ms(20022)
sqlite.pro.cache 294ms(20023)

Array - Contains OR

Demonstrates filtering by multiple array elements using Contains with OR.
Finds employees who have any of the specified skills.
Pro feature: multiple array operations in single query.
var sw = Stopwatch.StartNew();

// Find employees who have C# OR Python skill
var query = redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && 
        (e.Skills.Contains("C#") || e.Skills.Contains("Python")))
    .Take(100);

// Uncomment to see generated SQL:
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine(sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && 
        (e.Skills.Contains("C#") || e.Skills.Contains("Python")))
    .CountAsync();

sw.Stop();

var csharpCount = results.Count(e => e.Props.Skills?.Contains("C#") == true);
var pythonCount = results.Count(e => e.Props.Skills?.Contains("Python") == true);
ArrayContainsORIRedbQueryable.WhereArray.Contains
PG Pro 203ms(30094)
postgres.ef 1215ms(30093)
postgres.pro.repeat 170ms(30095)
postgres.pro.cache 167ms(30096)
postgres.ef.repeat 1162ms(30094)
MS Pro 435ms(30064)
mssql.pro.repeat 1518ms(30065)
mssql.pro.cache 910ms(30066)
sqlite.pro 171ms(30031)
sqlite.pro.repeat 182ms(30032)
sqlite.pro.cache 171ms(30033)

Array - Contains AND

Demonstrates filtering by multiple array elements using Contains with AND.
Finds employees who have ALL of the specified skills.
Pro feature: multiple array operations with AND logic.
var sw = Stopwatch.StartNew();

// Find employees who have BOTH C# AND SQL skills (full-stack)
var query = redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && 
        e.Skills.Contains("C#") && e.Skills.Contains("SQL"))
    .Take(100);

// Uncomment to see generated SQL:
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine(sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => e.Skills != null && 
        e.Skills.Contains("C#") && e.Skills.Contains("SQL"))
    .CountAsync();

sw.Stop();

var skillSamples = results.Take(3)
    .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills ?? [])}]");
ArrayContainsANDIRedbQueryable.WhereArray.Contains
PG Pro 179ms(20064)
postgres.ef 1029ms(20063)
postgres.pro.repeat 106ms(20065)
postgres.pro.cache 109ms(20066)
postgres.ef.repeat 1092ms(20064)
MS Pro 377ms(20044)
mssql.pro.repeat 346ms(20045)
mssql.pro.cache 341ms(20046)
sqlite.pro 193ms(20021)
sqlite.pro.repeat 113ms(20022)
sqlite.pro.cache 116ms(20023)

Scalar + Array Combined

Demonstrates combining scalar field filter with array Contains filter.
Finds senior developers (Age > 30) who have specific skills.
Pro feature: mixed scalar and array expressions in single query.
var sw = Stopwatch.StartNew();

// Find senior developers: Age > 30 AND has C# skill
var query = redb.Query<EmployeeProps>()
    .Where(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#"))
    .Take(100);

// Uncomment to see generated SQL:
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine(sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#"))
    .CountAsync();

sw.Stop();

var avgAge = results.Any() ? results.Average(e => e.Props.Age) : 0;
var sample = results.FirstOrDefault();
ArrayScalarCombinedIRedbQueryable.WhereArray.Contains
PG Pro 185ms(15045)
postgres.ef 1038ms(15045)
postgres.pro.repeat 163ms(15045)
postgres.pro.cache 149ms(15045)
postgres.ef.repeat 944ms(15045)
MS Pro 385ms(15030)
mssql.pro.repeat 1202ms(15030)
mssql.pro.cache 366ms(15030)
sqlite.pro 302ms(15015)
sqlite.pro.repeat 186ms(15015)
sqlite.pro.cache 171ms(15015)

String.Length Filter

Demonstrates String.Length property in Where clause.
Server-side: LENGTH() in PostgreSQL, LEN() in MSSQL.
Pro feature: string property access in expressions.
var sw = Stopwatch.StartNew();

// Find employees with long last names (> 6 characters)
var query = redb.Query<EmployeeProps>()
    .Where(e => e.LastName.Length > 6)
    .Take(100);

// Uncomment to see generated SQL (contains LENGTH or LEN):
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine(sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => e.LastName.Length > 6)
    .CountAsync();

sw.Stop();

var names = results.Take(5)
    .Select(e => $"{e.Props.LastName} ({e.Props.LastName.Length} chars)");
StringLengthPropertyIRedbQueryable.WhereString.Length
PG Pro 155ms(100264)
postgres.ef 1004ms(100263)
postgres.pro.repeat 95ms(100265)
postgres.pro.cache 98ms(100266)
postgres.ef.repeat 1070ms(100264)
MS Pro 135ms(100174)
mssql.pro.repeat 95ms(100175)
mssql.pro.cache 75ms(100176)
sqlite.pro 418ms(100081)
sqlite.pro.repeat 332ms(100082)
sqlite.pro.cache 271ms(100083)

TreeQuery - GroupBy

Demonstrates GroupBy aggregation on TreeQuery.
Groups tree nodes and calculates aggregates (SUM, COUNT) within tree context.
Pro feature: TreeQuery + GroupBy for hierarchical data analysis.
var sw = Stopwatch.StartNew();

// Ensure tree data exists (from E089_TreeCreate)
var root = await redb.TreeQuery<DepartmentProps>().WhereRoots().FirstOrDefaultAsync();
if (root == null)
{
    sw.Stop();
    return Fail("E173", "TreeQuery - GroupBy", ExampleTier.Free, sw.ElapsedMilliseconds,
        "No tree data found. Please run E089_TreeCreate first.");
}

// Group departments by IsActive status and aggregate budget
var groupedQuery = redb.TreeQuery<DepartmentProps>(root.Id)
    .Where(d => d.Budget > 0)
    .GroupBy(d => d.IsActive);

// Uncomment to see generated SQL:
// var sql = await groupedQuery.ToSqlStringAsync(g => new { 
//     IsActive = g.Key, 
//     TotalBudget = Agg.Sum(g, d => d.Budget),
//     Count = Agg.Count(g)
// });
// Console.WriteLine(sql);

var results = await groupedQuery.SelectAsync(g => new
{
    IsActive = g.Key,
    TotalBudget = Agg.Sum(g, d => d.Budget),
    DeptCount = Agg.Count(g)
});

sw.Stop();

var output = results.Select(r => 
    $"Active={r.IsActive}: {r.DeptCount} depts, Budget=${r.TotalBudget:N0}").ToArray();
TreeGroupByAggregationITreeQueryable.GroupByAgg.SumAgg.Count
PG Pro 81ms(1)
postgres.pro.repeat 26ms(1)
postgres.pro.cache 25ms(1)
MS Pro 44ms(1)
mssql.pro.repeat 31ms(1)
mssql.pro.cache 23ms(1)
sqlite.pro 20ms(1)
sqlite.pro.repeat 1ms(1)
sqlite.pro.cache 2ms(1)

TreeQuery - Window Functions

Demonstrates Window Functions on TreeQuery.
Calculates ROW_NUMBER and running totals within tree hierarchy.
Pro feature: TreeQuery + Window for hierarchical rankings and cumulative values.
var sw = Stopwatch.StartNew();

// Ensure tree data exists (from E089_TreeCreate)
var root = await redb.TreeQuery<DepartmentProps>().WhereRoots().FirstOrDefaultAsync();
if (root == null)
{
    sw.Stop();
    return Fail("E174", "TreeQuery - Window Functions", ExampleTier.Free, sw.ElapsedMilliseconds,
        "No tree data found. Please run E089_TreeCreate first.");
}

// Window functions on tree: rank departments by budget within the hierarchy
var windowQuery = redb.TreeQuery<DepartmentProps>(root.Id)
    .Where(d => d.Budget > 0)
    .Take(20)
    .WithWindow(w => w
        .PartitionBy(d => d.IsActive)
        .OrderByDesc(d => d.Budget));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(d => new {
//     d.Props.Name,
//     d.Props.Budget,
//     Rank = Win.RowNumber(),
//     RunningBudget = Win.Sum(d.Props.Budget)
// });
// Console.WriteLine(sql);

var results = await windowQuery.SelectAsync(d => new
{
    Name = d.Props.Name,
    Budget = d.Props.Budget,
    IsActive = d.Props.IsActive,
    Rank = Win.RowNumber(),
    RunningBudget = Win.Sum(d.Props.Budget)
});

sw.Stop();

var output = results.Take(5).Select(r => 
    $"#{r.Rank} {r.Name}: ${r.Budget:N0} (Running: ${r.RunningBudget:N0})").ToArray();
TreeWindowRowNumberRunningSumITreeQueryable.WithWindowWin.RowNumberWin.Sum
PG Pro 81ms(20)
postgres.pro.repeat 28ms(20)
postgres.pro.cache 29ms(20)
MS Pro 59ms(20)
mssql.pro.repeat 26ms(20)
mssql.pro.cache 19ms(20)
sqlite.pro 19ms(20)
sqlite.pro.repeat 2ms(20)
sqlite.pro.cache 3ms(20)

TreeQuery - GroupBy + Window

Demonstrates GroupBy + Window Functions on TreeQuery.
First groups tree nodes, then applies window functions to rank the groups.
Pro feature: TreeQuery + GroupBy + Window for advanced hierarchical analytics.
var sw = Stopwatch.StartNew();

// Ensure tree data exists (from E089_TreeCreate)
var root = await redb.TreeQuery<DepartmentProps>().WhereRoots().FirstOrDefaultAsync();
if (root == null)
{
    sw.Stop();
    return Fail("E175", "TreeQuery - GroupBy + Window", ExampleTier.Free, sw.ElapsedMilliseconds,
        "No tree data found. Please run E089_TreeCreate first.");
}

// GroupBy + Window: group by IsActive, then rank groups by total budget
var groupedWindowQuery = redb.TreeQuery<DepartmentProps>(root.Id)
    .Where(d => d.Budget > 0)
    .GroupBy(d => d.IsActive)
    .WithWindow(w => w
        .OrderByDesc(g => Agg.Sum(g, d => d.Budget)));

// Uncomment to see generated SQL:
// var sql = await groupedWindowQuery.ToSqlStringAsync(g => new {
//     IsActive = g.Key,
//     TotalBudget = Agg.Sum(g, d => d.Budget),
//     DeptCount = Agg.Count(g),
//     Rank = Win.RowNumber()
// });
// Console.WriteLine(sql);

var results = await groupedWindowQuery.SelectAsync(g => new
{
    IsActive = g.Key,
    TotalBudget = Agg.Sum(g, d => d.Budget),
    DeptCount = Agg.Count(g),
    Rank = Win.RowNumber()
});

sw.Stop();

var output = results.Select(r => 
    $"#{r.Rank} Active={r.IsActive}: {r.DeptCount} depts, Total=${r.TotalBudget:N0}").ToArray();
TreeGroupByWindowCombinedITreeQueryable.GroupByIGroupedQueryable.WithWindowWin.RowNumber
PG Pro 73ms(1)
postgres.pro.repeat 26ms(1)
postgres.pro.cache 28ms(1)
MS Pro 52ms(1)
mssql.pro.repeat 21ms(1)
mssql.pro.cache 16ms(1)
sqlite.pro 17ms(1)
sqlite.pro.repeat 1ms(1)
sqlite.pro.cache 1ms(1)

TreeQuery - DistinctBy

Demonstrates DistinctBy on TreeQuery to get unique tree nodes by a Props field.
Useful for removing duplicates based on specific property values.
Pro feature: DistinctBy with tree context.
var sw = Stopwatch.StartNew();

// Ensure tree data exists (from E089_TreeCreate)
var root = await redb.TreeQuery<DepartmentProps>().WhereRoots().FirstOrDefaultAsync();
if (root == null)
{
    sw.Stop();
    return Fail("E176", "TreeQuery - DistinctBy", ExampleTier.Free, sw.ElapsedMilliseconds,
        "No tree data found. Please run E089_TreeCreate first.");
}

// Get total count before distinct
var totalCount = await redb.TreeQuery<DepartmentProps>(root.Id).CountAsync();

// Get unique departments by IsActive status (will return max 2: true and false)
var query = redb.TreeQuery<DepartmentProps>(root.Id)
    .DistinctBy(d => d.IsActive)
    .Take(100);

// Uncomment to see generated SQL:
//var sql = query.ToSqlString();
//Console.WriteLine(sql);

var uniqueByStatus = await query.ToListAsync();

sw.Stop();

var statuses = uniqueByStatus.Select(d => $"IsActive={d.Props.IsActive}");
TreeDistinctByUniqueITreeQueryable.DistinctBy
PG Pro 78ms(1)
postgres.pro.repeat 24ms(1)
postgres.pro.cache 25ms(1)
MS Pro 78ms(1)
mssql.pro.repeat 35ms(1)
mssql.pro.cache 26ms(1)
sqlite.pro 4ms(1)
sqlite.pro.repeat 2ms(1)
sqlite.pro.cache 1ms(1)