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

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)

Window - Frame (Sliding)

Window function with custom frame (sliding window).
Calculate moving average over last N rows.
var sw = Stopwatch.StartNew();

var windowQuery = redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionBy(x => x.Department)
        .OrderBy(x => x.HireDate)
        .Frame(Frame.Rows(3)));  // ROWS BETWEEN 3 PRECEDING AND CURRENT ROW

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

var movingAvg = await windowQuery.SelectAsync(x => new
{
    Name = x.Props.FirstName,
    Salary = x.Props.Salary,
    MovingSum = Win.Sum(x.Props.Salary)  // Sum of last 4 rows (3 + current)
});

sw.Stop();

var sample = movingAvg.Skip(3).FirstOrDefault(); // Skip first 3 (partial windows)
WindowFrameSlidingMovingWindowBuilder.FrameFrame.Rows
PG Pro 235ms(50)
postgres.pro.repeat 220ms(50)
postgres.pro.cache 220ms(50)
MS Pro 232ms(50)
mssql.pro.repeat 278ms(50)
mssql.pro.cache 265ms(50)
sqlite.pro 255ms(50)
sqlite.pro.repeat 375ms(50)
sqlite.pro.cache 333ms(50)

Window - PartitionByRedb

PartitionByRedb in Window Functions - partition by base IRedbObject field.
SQL: PARTITION BY o._id_scheme (NO JOIN for partition key!)
var sw = Stopwatch.StartNew();

// Window with PartitionByRedb (base field) + OrderByDesc (Props field)
var ranked = await redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .PartitionByRedb(x => x.SchemeId)  // Base field - NO JOIN!
        .OrderByDesc(x => x.Salary))       // Props field
    .SelectAsync(x => new
    {
        x.Name,
        SchemeId = x.SchemeId,
        Salary = x.Props.Salary,
        RankInScheme = Win.RowNumber()
    });

sw.Stop();

var first = ranked.FirstOrDefault();
PartitionByRedbWindowNoJoinIWindowBuilder.PartitionByRedbWin.RowNumber
PG Pro 116ms(50)
postgres.pro.repeat 112ms(50)
postgres.pro.cache 112ms(50)
MS Pro 100ms(50)
mssql.pro.repeat 117ms(50)
mssql.pro.cache 164ms(50)
sqlite.pro 144ms(50)
sqlite.pro.repeat 211ms(50)
sqlite.pro.cache 186ms(50)

Window - OrderByRedb

OrderByRedb in Window Functions - order by base IRedbObject field.
SQL: ORDER BY o._date_create (NO JOIN for order key!)
var sw = Stopwatch.StartNew();

// Window with OrderByRedb (base field) + Frame
var ordered = await redb.Query<EmployeeProps>()
    .Take(50)
    .WithWindow(w => w
        .OrderByRedb(x => x.DateCreate)           // Base field - NO JOIN!
        .Frame(Frame.Rows().UnboundedPreceding()))
    .SelectAsync(x => new
    {
        x.Name,
        Created = x.DateCreate,
        Salary = x.Props.Salary,
        RunningCount = Win.Count()
    });

sw.Stop();

var last = ordered.LastOrDefault();
OrderByRedbWindowNoJoinIWindowBuilder.OrderByRedbWin.CountFrame.Rows
PG Pro 8ms(50)
postgres.pro.repeat 10ms(50)
postgres.pro.cache 6ms(50)
MS Pro 17ms(50)
mssql.pro.repeat 28ms(50)
mssql.pro.cache 21ms(50)
sqlite.pro 1ms(50)
sqlite.pro.repeat 1ms(50)
sqlite.pro.cache 1ms(50)

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)