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

GroupBy - With Filter

GroupBy with Where filter applied before grouping.
Filter employees by salary, then group by department; one aggregate reads a field two nested
classes deep (HomeAddress.Building.Floor).
var sw = Stopwatch.StartNew();

// Uncomment to see generated SQL:
//var sql = await redb.Query<EmployeeProps>()
//    .Where(x => x.Salary > 50000)
//    .GroupBy(x => x.Department)
//    .ToSqlStringAsync(g => new { Dept = g.Key, Count = Agg.Count(g) });
//Console.WriteLine(sql);

var byDeptFiltered = await redb.Query<EmployeeProps>()
    .Where(x => x.Salary > 50000m)
    .GroupBy(x => x.Department)
    .SelectAsync(g => new
    {
        Department = g.Key,
        TotalSalary = Agg.Sum(g, x => x.Salary),
        MaxFloor = Agg.Max(g, x => x.HomeAddress!.Building!.Floor),
        Count = Agg.Count(g)
    });

sw.Stop();

var first = byDeptFiltered.FirstOrDefault();
GroupByWhereFilterAnalyticsIRedbQueryable.GroupByIRedbQueryable.Where
PG Pro 309ms(5)
postgres.ef 181ms(5)
postgres.pro.repeat 308ms(5)
postgres.pro.cache 322ms(5)
postgres.ef.repeat 180ms(5)
MS Pro 104ms(5)
mssql.pro.repeat 133ms(5)
mssql.pro.cache 912ms(5)
sqlite.pro 291ms(5)
sqlite.pro.repeat 348ms(5)
sqlite.pro.cache 379ms(5)

GroupBy - by ListItem (Id/Value/Bare)

GroupBy by a ListItem-typed property.
Probes 3 flavors:
(1) GroupBy(p => p.Status!.Id) - key as long
(2) GroupBy(p => p.Status!.Value) - key as string
(3) GroupBy(p => p.Status) - the bare ListItem class as key
Pro/OSS parity check for grouping over RedbListItem fields.
Requires E114-E118 to run first.
var sw = Stopwatch.StartNew();
var notes = new List<string>();

// (1) GroupBy by Status.Id (long key)
try
{
    var q1 = redb.Query<PersonProps>().GroupBy(p => p.Status!.Id);
    // var sql1 = await q1.ToSqlStringAsync(g => new
    // {
        // StatusId = g.Key,
        // Count = Agg.Count(g),
        // AvgAge = Agg.Average(g, x => x.Age)
    // });
    // Console.WriteLine("[E130-SQL-1]\n" + sql1);
    var byId = await q1.SelectAsync(g => new
        {
            StatusId = g.Key,
            Count = Agg.Count(g),
            AvgAge = Agg.Average(g, x => x.Age)
        });
    notes.Add($"(1) by Status.Id: groups={byId.Count}; first=Id:{byId.FirstOrDefault()?.StatusId}, cnt={byId.FirstOrDefault()?.Count}");
}
catch (Exception ex)
{
    notes.Add($"(1) by Status.Id: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}");
    Console.WriteLine("[E130-1] " + ex);
}

// (2) GroupBy by Status.Value (string key)
try
{
    var q2 = redb.Query<PersonProps>().GroupBy(p => p.Status!.Value);
    // var sql2 = await q2.ToSqlStringAsync(g => new
    // {
        // StatusValue = g.Key,
        // Count = Agg.Count(g)
    // });
    // Console.WriteLine("[E130-SQL-2]\n" + sql2);
    var byValue = await q2.SelectAsync(g => new
        {
            StatusValue = g.Key,
            Count = Agg.Count(g)
        });
    notes.Add($"(2) by Status.Value: groups={byValue.Count}; first=\"{byValue.FirstOrDefault()?.StatusValue}\", cnt={byValue.FirstOrDefault()?.Count}");
}
catch (Exception ex)
{
    notes.Add($"(2) by Status.Value: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}");
    Console.WriteLine("[E130-2] " + ex);
}

// (3) GroupBy by bare Status (RedbListItem class itself)
try
{
    var q3 = redb.Query<PersonProps>().GroupBy(p => p.Status);
    // var sql3 = await q3.ToSqlStringAsync(g => new
    // {
        // Status = g.Key,
        // Count = Agg.Count(g)
    // });
    // Console.WriteLine("[E130-SQL-3]\n" + sql3);
    var byBare = await q3.SelectAsync(g => new
        {
            Status = g.Key,
            Count = Agg.Count(g)
        });
    var first = byBare.FirstOrDefault();
    var firstDesc = first?.Status is RedbListItem li
        ? $"Id:{li.Id}, Value:'{li.Value}'"
        : (first?.Status is null ? "null" : first.Status.ToString());
    notes.Add($"(3) by bare Status: groups={byBare.Count}; first={firstDesc}, cnt={first?.Count}");
}
catch (Exception ex)
{
    notes.Add($"(3) by bare Status: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}");
    Console.WriteLine("[E130-3] " + ex);
}

sw.Stop();
foreach (var n in notes) Console.WriteLine("[E130-NOTE] " + n);
GroupByListItemAggregationAnalyticsIRedbQueryable.GroupByRedbListItem
PG Pro 45ms(3)
postgres.pro.repeat 28ms(3)
postgres.pro.cache 23ms(3)
MS Pro 49ms(3)
mssql.pro.repeat 61ms(3)
mssql.pro.cache 56ms(3)
sqlite.pro 5ms(3)
sqlite.pro.repeat 2ms(3)
sqlite.pro.cache 1ms(3)

GroupBy - Composite Key

GroupBy with composite key (multiple fields).
Group by Department AND Position for detailed breakdown; one aggregate reads a field two nested
classes deep (HomeAddress.Building.Floor).
var sw = Stopwatch.StartNew();

// Uncomment to see generated SQL:
// var sql = await redb.Query<EmployeeProps>()
//     .GroupBy(x => new { x.Department, x.Position })
//     .ToSqlStringAsync(g => new { g.Key.Department, g.Key.Position, Count = Agg.Count(g) });
// Console.WriteLine(sql);

var byDeptPosition = await redb.Query<EmployeeProps>()
    .GroupBy(x => new { x.Department, x.Position })
    .SelectAsync(g => new
    {
        g.Key.Department,
        g.Key.Position,
        TotalSalary = Agg.Sum(g, x => x.Salary),
        AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor),
        Count = Agg.Count(g)
    });

sw.Stop();

var first = byDeptPosition.FirstOrDefault();
GroupByCompositeMultiKeyAnalyticsIRedbQueryable.GroupBy
PG Pro 220ms(6)
postgres.ef 250ms(6)
postgres.pro.repeat 214ms(6)
postgres.pro.cache 212ms(6)
postgres.ef.repeat 249ms(6)
MS Pro 1244ms(6)
mssql.pro.repeat 1347ms(6)
mssql.pro.cache 716ms(6)
sqlite.pro 306ms(5)
sqlite.pro.repeat 419ms(6)
sqlite.pro.cache 424ms(6)

GroupByRedb - Base Fields

GroupBy on base RedbObject fields without JOIN.
Groups by SchemeId or OwnerId directly from _objects table.
Much faster than GroupBy on Props fields.
var sw = Stopwatch.StartNew();

// Uncomment to see generated SQL:
// var sql = await redb.Query<EmployeeProps>()
//     .GroupByRedb(x => x.OwnerId)
//     .ToSqlStringAsync(g => new { Owner = g.Key, Count = Agg.Count(g) });
// Console.WriteLine(sql);

// GroupBy on base field (no JOIN with _values!)
var byOwner = await redb.Query<EmployeeProps>()
    .GroupByRedb(x => x.OwnerId)
    .SelectAsync(g => new
    {
        OwnerId = g.Key,
        TotalSalary = Agg.Sum(g, x => x.Salary),
        AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor),
        Count = Agg.Count(g)
    });

sw.Stop();

var first = byOwner.FirstOrDefault();
GroupByRedbBaseNoJoinAnalyticsIRedbQueryable.GroupByRedb
PG Pro 100ms(1)
postgres.ef 163ms(1)
postgres.pro.repeat 92ms(1)
postgres.pro.cache 95ms(1)
postgres.ef.repeat 161ms(1)
MS Pro 59ms(1)
mssql.pro.repeat 78ms(1)
mssql.pro.cache 81ms(1)
sqlite.pro 165ms(1)
sqlite.pro.repeat 222ms(1)
sqlite.pro.cache 188ms(1)

Window - RowNumber

Window function ROW_NUMBER() with PARTITION BY.
Ranks employees within each department by salary.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderByDesc(x => x.Salary));

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

var ranked = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Department = x.Props.Department,
    Salary = x.Props.Salary,
    Rank = Win.RowNumber()
});

sw.Stop();

var top = ranked.FirstOrDefault();
WindowRowNumberRankPartitionIRedbQueryable.WithWindowWin.RowNumber
PG Pro 200ms(50)
postgres.pro.repeat 187ms(50)
postgres.pro.cache 188ms(50)
MS Pro 198ms(50)
mssql.pro.repeat 221ms(50)
mssql.pro.cache 219ms(50)
sqlite.pro 231ms(50)
sqlite.pro.repeat 316ms(50)
sqlite.pro.cache 289ms(50)

Window - Running Sum

Window function SUM() OVER for running totals.
Calculates cumulative salary within each department.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderBy(x => x.HireDate));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(x => new { x.Props.Salary, Total = Win.Sum(x.Props.Salary) });
// Console.WriteLine(sql);

var running = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Department = x.Props.Department,
    Salary = x.Props.Salary,
    RunningTotal = Win.Sum(x.Props.Salary)
});

sw.Stop();

var sample = running.FirstOrDefault();
WindowSumRunningCumulativeIRedbQueryable.WithWindowWin.Sum
PG Pro 229ms(50)
postgres.pro.repeat 236ms(50)
postgres.pro.cache 227ms(50)
MS Pro 227ms(50)
mssql.pro.repeat 276ms(50)
mssql.pro.cache 268ms(50)
sqlite.pro 255ms(50)
sqlite.pro.repeat 335ms(50)
sqlite.pro.cache 384ms(50)

Window - Lag/Lead

Window functions LAG/LEAD for previous/next values.
Access previous and next employee salary in sequence.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderBy(x => x.Salary));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(x => new { Prev = Win.Lag(x.Props.Salary), Next = Win.Lead(x.Props.Salary) });
// Console.WriteLine(sql);

var withLagLead = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Salary = x.Props.Salary,
    PrevSalary = Win.Lag(x.Props.Salary),
    NextSalary = Win.Lead(x.Props.Salary)
});

sw.Stop();

var sample = withLagLead.Skip(1).FirstOrDefault(); // Skip first (no prev)
WindowLagLeadPreviousNextWin.LagWin.Lead
PG Pro 190ms(50)
postgres.pro.repeat 189ms(50)
postgres.pro.cache 186ms(50)
MS Pro 263ms(50)
mssql.pro.repeat 313ms(50)
mssql.pro.cache 312ms(50)
sqlite.pro 237ms(50)
sqlite.pro.repeat 346ms(50)
sqlite.pro.cache 300ms(50)

Window - Rank/DenseRank

Window functions RANK/DENSE_RANK for ranking with ties.
RANK skips numbers after ties, DENSE_RANK does not.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderByDesc(x => x.Salary));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(x => new { Rank = Win.Rank(), Dense = Win.DenseRank() });
// Console.WriteLine(sql);

var ranked = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Department = x.Props.Department,
    Salary = x.Props.Salary,
    Rank = Win.Rank(),
    DenseRank = Win.DenseRank()
});

sw.Stop();

var sample = ranked.FirstOrDefault();
WindowRankDenseRankRankingWin.RankWin.DenseRank
PG Pro 193ms(50)
postgres.pro.repeat 188ms(50)
postgres.pro.cache 191ms(50)
MS Pro 191ms(50)
mssql.pro.repeat 219ms(50)
mssql.pro.cache 216ms(50)
sqlite.pro 224ms(50)
sqlite.pro.repeat 372ms(50)
sqlite.pro.cache 286ms(50)

Window - Ntile

Window function NTILE for bucket distribution.
Divides employees into N equal groups (quartiles, deciles, etc.).
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(100)
    .WithWindow(w => w.OrderByDesc(x => x.Salary));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(x => new { Quartile = Win.Ntile(4) });
// Console.WriteLine(sql);

// Divide into 4 quartiles by salary
var quartiles = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Salary = x.Props.Salary,
    Quartile = Win.Ntile(4)
});

sw.Stop();

var q1Count = quartiles.Count(x => x.Quartile == 1);
var topEarner = quartiles.FirstOrDefault();
WindowNtileQuartileBucketWin.Ntile
PG Pro 119ms(100)
postgres.pro.repeat 112ms(100)
postgres.pro.cache 111ms(100)
MS Pro 114ms(100)
mssql.pro.repeat 141ms(100)
mssql.pro.cache 281ms(100)
sqlite.pro 155ms(100)
sqlite.pro.repeat 248ms(100)
sqlite.pro.cache 195ms(100)

Window - FirstValue/LastValue

Window functions FIRST_VALUE/LAST_VALUE.
Get first and last salary in partition for comparison.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderByDesc(x => x.Salary));

// Uncomment to see generated SQL:
// var sql = await windowQuery.ToSqlStringAsync(x => new { Max = Win.FirstValue(x.Props.Salary), Min = Win.LastValue(x.Props.Salary) });
// Console.WriteLine(sql);

var withMinMax = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Department = x.Props.Department,
    Salary = x.Props.Salary,
    MaxInDept = Win.FirstValue(x.Props.Salary),  // First = highest (DESC order)
    MinInDept = Win.LastValue(x.Props.Salary)    // Last = lowest
});

sw.Stop();

var sample = withMinMax.FirstOrDefault();
WindowFirstValueLastValueWin.FirstValueWin.LastValue
PG Pro 195ms(50)
postgres.pro.repeat 189ms(50)
postgres.pro.cache 185ms(50)
MS Pro 206ms(50)
mssql.pro.repeat 237ms(50)
mssql.pro.cache 239ms(50)
sqlite.pro 225ms(50)
sqlite.pro.repeat 359ms(50)
sqlite.pro.cache 299ms(50)