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 - 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)

DistinctRedb - Find Duplicates

DISTINCT ON base fields (without Id) for finding duplicates.
Finds objects with identical Name, CodeInt etc. (potential duplicates).
var sw = Stopwatch.StartNew();

var query = redb.Query<EmployeeProps>()
    .DistinctRedb()
    .Take(100);

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

var unique = await query.ToListAsync();

sw.Stop();
DistinctDistinctRedbDuplicatesIRedbQueryable.DistinctRedb
PG Pro 245ms(100)
postgres.ef 1046ms(100)
postgres.pro.repeat 226ms(100)
postgres.pro.cache 220ms(100)
postgres.ef.repeat 1092ms(100)
MS Pro 238ms(100)
mssql.pro.repeat 259ms(100)
mssql.pro.cache 237ms(100)
sqlite.pro 255ms(100)
sqlite.pro.repeat 387ms(100)
sqlite.pro.cache 328ms(100)

DistinctByRedb - By Field

DISTINCT ON specific base field.
Get one object per unique Name (first by Id).
var sw = Stopwatch.StartNew();

var query = redb.Query<EmployeeProps>()
    .DistinctByRedb(x => x.Name)
    .Take(100);

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

var uniqueByName = await query.ToListAsync();

sw.Stop();

var names = string.Join(", ", uniqueByName.Take(3).Select(x => x.name));
DistinctDistinctByRedbUniqueIRedbQueryable.DistinctByRedb
PG Pro 77ms(100)
postgres.ef 466ms(100)
postgres.pro.repeat 70ms(100)
postgres.pro.cache 70ms(100)
postgres.ef.repeat 443ms(100)
MS Pro 82ms(100)
mssql.pro.repeat 77ms(100)
mssql.pro.cache 68ms(100)
sqlite.pro 177ms(100)
sqlite.pro.repeat 266ms(100)
sqlite.pro.cache 254ms(100)

WhereInRedb - Base Field

Filter by list of base field values.
WHERE o._id IN (...) without JOIN - very fast.
var sw = Stopwatch.StartNew();

// First get some IDs to filter by
var sampleIds = await redb.Query<EmployeeProps>()
    .Take(5)
    .Select(x => x.id)
    .ToListAsync();

if (sampleIds.Count == 0)
{
    sw.Stop();
    return Fail("E141", "WhereInRedb - Base Field", ExampleTier.Free, sw.ElapsedMilliseconds,
        "No employees found. Run E000 first.");
}

var query = redb.Query<EmployeeProps>()
    .WhereInRedb(x => x.Id, sampleIds);

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

var results = await query.ToListAsync();

sw.Stop();
WhereInWhereInRedbBaseFilterIRedbQueryable.WhereInRedb
PG Pro 40ms(5)
postgres.ef 919ms(5)
postgres.pro.repeat 35ms(5)
postgres.pro.cache 19ms(5)
postgres.ef.repeat 924ms(5)
MS Pro 46ms(5)
mssql.pro.repeat 32ms(5)
mssql.pro.cache 29ms(5)
sqlite.pro 5ms(5)
sqlite.pro.repeat 3ms(5)
sqlite.pro.cache 3ms(5)

GroupByArray - Array Elements

Groups objects by elements of an array field using GroupByArray.
Expands arrays to create one group per element (e.g., group by each Contact.Type).
var sw = Stopwatch.StartNew();

// Group by each Contact.Type (email, phone, etc.)
// This expands the Contacts[] array and groups by contact type
var byContactType = await redb.Query<EmployeeProps>()
    .Where(e => e.Contacts != null)
    .GroupByArray(e => e.Contacts!, c => c.Type)
    .SelectAsync(g => new
    {
        ContactType = g.Key,
        EmployeeCount = Agg.Count(g)
    });

// Uncomment to see generated SQL:
// var sql = await redb.Query<EmployeeProps>()
//     .GroupByArray(e => e.Contacts!, c => c.Type)
//     .ToSqlStringAsync(g => new { g.Key, Agg.Count(g) });
// Console.WriteLine(sql);

sw.Stop();

var output = byContactType.OrderByDescending(g => g.EmployeeCount)
    .Select(g => $"{g.ContactType}: {g.EmployeeCount} employees").ToArray();
GroupByArrayArrayExpandIRedbQueryable.GroupByArray
PG Pro 618ms(2)
postgres.ef 172ms(2)
postgres.pro.repeat 558ms(2)
postgres.pro.cache 542ms(2)
postgres.ef.repeat 156ms(2)
MS Pro 912ms(2)
mssql.pro.repeat 921ms(2)
mssql.pro.cache 1414ms(2)
sqlite.pro 682ms(2)
sqlite.pro.repeat 659ms(2)
sqlite.pro.cache 639ms(2)

SumRedbAsync - Base Field Sum

SumRedbAsync - sum of base IRedbObject field WITHOUT JOIN to _values.
Much faster than SumAsync for base fields like Id.
var sw = Stopwatch.StartNew();

// Sum of base field Id (from _objects table, NO JOIN with _values!)
var sumId = await redb.Query<EmployeeProps>().SumRedbAsync(x => x.Id);

// Compare with regular count
var count = await redb.Query<EmployeeProps>().CountAsync();

sw.Stop();
SumRedbAsyncAggregationNoJoinIRedbQueryable.SumRedbAsync
PG Pro 38ms(100307)
postgres.ef 35ms(100306)
postgres.pro.repeat 34ms(100308)
postgres.pro.cache 33ms(100309)
postgres.ef.repeat 32ms(100307)
MS Pro 39ms(100207)
mssql.pro.repeat 38ms(100208)
mssql.pro.cache 40ms(100209)
sqlite.pro 14ms(100101)
sqlite.pro.repeat 17ms(100105)
sqlite.pro.cache 17ms(100106)

Min/MaxRedbAsync - Date Range

MinRedbAsync/MaxRedbAsync - min/max of base IRedbObject fields WITHOUT JOIN.
Perfect for finding date ranges (DateCreate, DateModify).
var sw = Stopwatch.StartNew();

// Min/Max of DateCreate (from _objects table, NO JOIN!)
var minDate = await redb.Query<EmployeeProps>().MinRedbAsync(x => x.DateCreate);
var maxDate = await redb.Query<EmployeeProps>().MaxRedbAsync(x => x.DateCreate);

sw.Stop();

var range = minDate.HasValue && maxDate.HasValue 
    ? (maxDate.Value - minDate.Value).Days 
    : 0;
MinRedbAsyncMaxRedbAsyncDateRangeIRedbQueryable.MinRedbAsyncIRedbQueryable.MaxRedbAsync
PG Pro 85ms(2)
postgres.ef 87ms(2)
postgres.pro.repeat 80ms(2)
postgres.pro.cache 81ms(2)
postgres.ef.repeat 87ms(2)
MS Pro 18ms(2)
mssql.pro.repeat 21ms(2)
mssql.pro.cache 22ms(2)
sqlite.pro 33ms(2)
sqlite.pro.repeat 48ms(2)
sqlite.pro.cache 40ms(2)

AverageRedbAsync - Base Field Avg

AverageRedbAsync - average of base IRedbObject field WITHOUT JOIN.
Useful for statistics on Id distribution.
var sw = Stopwatch.StartNew();

// Average of base field Id (from _objects table, NO JOIN!)
var avgId = await redb.Query<EmployeeProps>().AverageRedbAsync(x => x.Id);

// Get min/max for context
var minId = await redb.Query<EmployeeProps>().MinRedbAsync(x => x.Id);
var maxId = await redb.Query<EmployeeProps>().MaxRedbAsync(x => x.Id);

sw.Stop();
AverageRedbAsyncAggregationNoJoinIRedbQueryable.AverageRedbAsync
PG Pro 66ms(1)
postgres.ef 46ms(1)
postgres.pro.repeat 61ms(1)
postgres.pro.cache 60ms(1)
postgres.ef.repeat 37ms(1)
MS Pro 46ms(1)
mssql.pro.repeat 54ms(1)
mssql.pro.cache 52ms(1)
sqlite.pro 34ms(1)
sqlite.pro.repeat 46ms(1)
sqlite.pro.cache 42ms(1)

AggregateRedbAsync - Batch Base

AggregateRedbAsync - batch aggregation of base IRedbObject fields in ONE query.
Combines Sum, Min, Max, Avg, Count on base fields WITHOUT JOIN.
var sw = Stopwatch.StartNew();

// Multiple aggregations on base fields in ONE query (NO JOIN!)
var stats = await redb.Query<EmployeeProps>()
    .AggregateRedbAsync(x => new
    {
        MaxId = Agg.Max(x.Id),
        MinDateCreate = Agg.Min(x.DateCreate),
        MaxDateModify = Agg.Max(x.DateModify),
        AvgId = Agg.Average(x.Id),
        Count = Agg.Count()
    });

sw.Stop();
AggregateRedbAsyncBatchNoJoinIRedbQueryable.AggregateRedbAsyncAgg.SumAgg.MinAgg.Max
PG Pro 35ms(100307)
postgres.ef 101ms(100306)
postgres.pro.repeat 32ms(100308)
postgres.pro.cache 32ms(100309)
postgres.ef.repeat 102ms(100307)
MS Pro 49ms(100207)
mssql.pro.repeat 51ms(100208)
mssql.pro.cache 49ms(100209)
sqlite.pro 24ms(100101)
sqlite.pro.repeat 30ms(100105)
sqlite.pro.cache 31ms(100106)

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)