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

Props - List<ListItem>

Object with List of ListItems field in Props.
Shows how to store multiple list item references (e.g. roles, tags).
Requires E114+E115 to run first.
var sw = Stopwatch.StartNew();

// Get existing list
var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses");
if (list == null)
{
    sw.Stop();
    return Fail("E119", "Props - List<ListItem>", ExampleTier.Free, sw.ElapsedMilliseconds,
        "List 'ExampleStatuses' not found. Run E114 first.");
}

// Get list items
var items = await redb.ListProvider.GetListItemsAsync(list.Id);
if (items.Count < 2)
{
    sw.Stop();
    return Fail("E119", "Props - List<ListItem>", ExampleTier.Free, sw.ElapsedMilliseconds,
        "Need at least 2 items. Run E115 first.");
}

// Sync Person scheme
await redb.SyncSchemeAsync<PersonProps>();

// Create person with Roles field (List<ListItem>)
var person = new RedbObject<PersonProps>
{
    name = "Jane Smith",
    Props = new PersonProps
    {
        Name = "Jane Smith",
        Age = 28,
        Email = "jane@example.com",
        Roles = items.Take(3).ToList()  // Multiple ListItem references
    }
};

// Uncomment to see generated SQL:
// (Save uses COPY protocol for Pro)

var personId = await redb.SaveAsync(person);

// Load back to verify
redb.PropsCache.Clear();
var loaded = await redb.LoadAsync<PersonProps>(personId);

sw.Stop();

var rolesCount = loaded?.Props?.Roles?.Count ?? 0;
var rolesList = loaded?.Props?.Roles != null 
    ? string.Join(", ", loaded.Props.Roles.Select(r => r.Value))
    : "N/A";
PropsListItemArrayRolesList<RedbListItem>
PG Pro 114ms(3)
postgres.ef 77ms(3)
postgres.pro.repeat 90ms(3)
postgres.pro.cache 95ms(3)
postgres.ef.repeat 46ms(3)
MS Pro 174ms(3)
mssql.pro.repeat 148ms(3)
mssql.pro.cache 137ms(3)
sqlite.pro 8ms(3)
sqlite.pro.repeat 4ms(3)
sqlite.pro.cache 5ms(3)

ListItem - Where by Value

Query filtering by ListItem.Value property.
Shows how to filter objects by the Value of a ListItem field.
Requires E114-E118 to run first.
var sw = Stopwatch.StartNew();

// Query persons where Status.Value == "Active"
var query = redb.Query<PersonProps>()
    .Where(p => p.Status!.Value == "Active")
    .Take(100);

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

var results = await query.ToListAsync();

sw.Stop();

if (results.Count == 0)
{
    return Ok("E120", "ListItem - Where by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["No persons with Status='Active' found", "Run E118 first to create test data"]);
}

var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A";
ListItemWhereValueQueryIRedbQueryable.WhereRedbListItem.Value
PG Pro 51ms(1)
postgres.ef 60ms(1)
postgres.pro.repeat 34ms(1)
postgres.pro.cache 34ms(1)
postgres.ef.repeat 52ms(1)
MS Pro 51ms(1)
mssql.pro.repeat 38ms(1)
mssql.pro.cache 32ms(1)
sqlite.pro 1ms(1)
sqlite.pro.repeat 1ms(1)
sqlite.pro.cache 1ms(1)

ListItem - WhereIn by Value

Query filtering by ListItem.Value using WhereIn.
Shows how to filter objects by multiple ListItem values at once.
Requires E114-E118 to run first.
var sw = Stopwatch.StartNew();

// Query persons where Status.Value in ["Active", "Pending"]
var targetValues = new[] { "Active", "Pending", "Blocked" };
var query = redb.Query<PersonProps>()
    .WhereIn(p => p.Status!.Value, targetValues)
    .Take(100);

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

var results = await query.ToListAsync();

sw.Stop();

if (results.Count == 0)
{
    return Ok("E121", "ListItem - WhereIn by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        [$"Filter: Status.Value IN [{string.Join(", ", targetValues)}]", "No matching persons found"]);
}

var statuses = results.Select(r => r.Props?.Status?.Value ?? "N/A").Distinct();
ListItemWhereInValueQueryIRedbQueryable.WhereInRedbListItem.Value
PG Pro 35ms(1)
postgres.ef 57ms(1)
postgres.pro.repeat 8ms(1)
postgres.pro.cache 8ms(1)
postgres.ef.repeat 53ms(1)
MS Pro 41ms(1)
mssql.pro.repeat 47ms(1)
mssql.pro.cache 45ms(1)
sqlite.pro 0ms(1)
sqlite.pro.repeat 0ms(1)
sqlite.pro.cache 0ms(1)

ListItem - Direct Compare

Query filtering by direct ListItem comparison.
Shows how to compare ListItem field with a ListItem instance directly.
Requires E114-E118 to run first.
var sw = Stopwatch.StartNew();

// Get a ListItem to compare against
var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses");
if (list == null)
{
    sw.Stop();
    return Fail("E122", "ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds,
        "List 'ExampleStatuses' not found. Run E114 first.");
}

var items = await redb.ListProvider.GetListItemsAsync(list.Id);
var activeItem = items.FirstOrDefault(i => i.Value == "Active");
if (activeItem == null)
{
    sw.Stop();
    return Fail("E122", "ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds,
        "Item 'Active' not found. Run E115 first.");
}

// Query persons where Status == activeItem (by ID)
var query = redb.Query<PersonProps>()
    .Where(p => p.Status == activeItem)
    .Take(100);

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

var results = await query.ToListAsync();

sw.Stop();
ListItemWhereCompareQueryIRedbQueryable.WhereRedbListItem
PG Pro 40ms(1)
postgres.ef 73ms(1)
postgres.pro.repeat 8ms(1)
postgres.pro.cache 8ms(1)
postgres.ef.repeat 63ms(1)
MS Pro 51ms(1)
mssql.pro.repeat 8ms(1)
mssql.pro.cache 7ms(1)
sqlite.pro 1ms(1)
sqlite.pro.repeat 0ms(1)
sqlite.pro.cache 0ms(1)

ListItem Array - Any

Query filtering by ListItem array using Any().
Shows how to filter objects where any element in ListItem array matches condition.
Requires E114-E119 to run first.
var sw = Stopwatch.StartNew();

// Query persons where any Role has Value == "Active"
var query = redb.Query<PersonProps>()
    .Where(p => p.Roles!.Any(r => r.Value == "Active"))
    .Take(100);

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

var results = await query.ToListAsync();

sw.Stop();

if (results.Count == 0)
{
    return Ok("E123", "ListItem Array - Any", ExampleTier.Free, sw.ElapsedMilliseconds, 0,
        ["Filter: Roles.Any(r => r.Value == 'Active')", "No matching persons found. Run E119 first."]);
}

var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A";
var rolesCount = results.FirstOrDefault()?.Props?.Roles?.Count ?? 0;
ListItemArrayAnyQueryIRedbQueryable.WhereList<RedbListItem>.Any
PG Pro 46ms(1)
postgres.ef 61ms(1)
postgres.pro.repeat 6ms(1)
postgres.pro.cache 8ms(1)
postgres.ef.repeat 60ms(1)
MS Pro 50ms(1)
mssql.pro.repeat 7ms(1)
mssql.pro.cache 8ms(1)
sqlite.pro 1ms(1)
sqlite.pro.repeat 0ms(1)
sqlite.pro.cache 0ms(1)

SumAsync - Total

Calculates sum of a numeric field using SumAsync.
Server-side aggregation without loading objects, over a field of the employee and over a field
two nested classes deep (HomeAddress.Building.Floor).
var sw = Stopwatch.StartNew();

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

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

var totalSalary = await query.SumAsync(e => e.Salary);
var totalFloor = await query.SumAsync(e => e.HomeAddress!.Building!.Floor);

sw.Stop();
SumAggregationAnalyticsIRedbQueryable.SumAsync
PG Pro 93ms(2)
postgres.ef 111ms(2)
postgres.pro.repeat 86ms(2)
postgres.pro.cache 86ms(2)
postgres.ef.repeat 94ms(2)
MS Pro 138ms(2)
mssql.pro.repeat 106ms(2)
mssql.pro.cache 96ms(2)
sqlite.pro 234ms(2)
sqlite.pro.repeat 303ms(2)
sqlite.pro.cache 359ms(2)

AverageAsync - Mean

Calculates average of a numeric field using AverageAsync.
Server-side aggregation without loading objects, over a field of the employee and over a field
two nested classes deep (HomeAddress.Building.Floor).
var sw = Stopwatch.StartNew();

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

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

var avgAge = await query.AverageAsync(e => e.Age);
var avgFloor = await query.AverageAsync(e => e.HomeAddress!.Building!.Floor);

sw.Stop();
AverageAvgAggregationAnalyticsIRedbQueryable.AverageAsync
PG Pro 82ms(2)
postgres.ef 93ms(2)
postgres.pro.repeat 80ms(2)
postgres.pro.cache 83ms(2)
postgres.ef.repeat 86ms(2)
MS Pro 80ms(2)
mssql.pro.repeat 96ms(2)
mssql.pro.cache 118ms(2)
sqlite.pro 154ms(2)
sqlite.pro.repeat 199ms(2)
sqlite.pro.cache 233ms(2)

MinAsync/MaxAsync - Range

Calculates min and max of numeric fields using MinAsync/MaxAsync.
Server-side aggregation without loading objects, over a field of the employee and over a field
two nested classes deep (HomeAddress.Building.Floor).
var sw = Stopwatch.StartNew();

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

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

var minSalary = await query.MinAsync(e => e.Salary);
var maxSalary = await query.MaxAsync(e => e.Salary);
var minFloor = await query.MinAsync(e => e.HomeAddress!.Building!.Floor);
var maxFloor = await query.MaxAsync(e => e.HomeAddress!.Building!.Floor);

sw.Stop();
MinMaxAggregationAnalyticsIRedbQueryable.MinAsyncIRedbQueryable.MaxAsync
PG Pro 177ms(4)
postgres.ef 171ms(4)
postgres.pro.repeat 169ms(4)
postgres.pro.cache 170ms(4)
postgres.ef.repeat 163ms(4)
MS Pro 183ms(4)
mssql.pro.repeat 206ms(4)
mssql.pro.cache 180ms(4)
sqlite.pro 341ms(4)
sqlite.pro.repeat 439ms(4)
sqlite.pro.cache 465ms(4)

AggregateAsync - Batch

Batch aggregation with multiple functions in single query.
Calculates Sum, Avg, Min, Max, Count in ONE SQL request, over fields of the employee and over a field
two nested classes deep (HomeAddress.Building.Floor): for redb a nested field is just another structure.
var sw = Stopwatch.StartNew();

// Multiple aggregations in ONE query (Pro PVT-based)
var stats = await redb.Query<EmployeeProps>()
    .AggregateAsync(x => new
    {
        TotalSalary = Agg.Sum(x.Props.Salary),
        AvgAge = Agg.Average(x.Props.Age),
        MinSalary = Agg.Min(x.Props.Salary),
        MaxSalary = Agg.Max(x.Props.Salary),
        MinFloor = Agg.Min(x.Props.HomeAddress!.Building!.Floor),
        MaxFloor = Agg.Max(x.Props.HomeAddress!.Building!.Floor),
        AvgFloor = Agg.Average(x.Props.HomeAddress!.Building!.Floor),
        Count = Agg.Count()
    });

sw.Stop();
AggregateBatchSumAvgCountIRedbQueryable.AggregateAsyncAgg.SumAgg.AverageAgg.Count
PG Pro 138ms(100307)
postgres.ef 250ms(100306)
postgres.pro.repeat 124ms(100308)
postgres.pro.cache 126ms(100309)
postgres.ef.repeat 227ms(100307)
MS Pro 93ms(100207)
mssql.pro.repeat 133ms(100208)
mssql.pro.cache 120ms(100209)
sqlite.pro 175ms(100101)
sqlite.pro.repeat 207ms(100105)
sqlite.pro.cache 254ms(100106)

GroupBy - Simple

Groups objects by a field and calculates aggregates per group.
SQL: GROUP BY Department with SUM, AVG, COUNT, plus AVG over 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 => x.Department)
//     .ToSqlStringAsync(g => new { Dept = g.Key, Total = Agg.Sum(g, x => x.Salary) });
// Console.WriteLine(sql);

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

sw.Stop();

var first = byDept.FirstOrDefault();
GroupByAggregationAnalyticsIRedbQueryable.GroupByIGroupedQueryable.SelectAsync
PG Pro 195ms(6)
postgres.ef 187ms(6)
postgres.pro.repeat 181ms(6)
postgres.pro.cache 182ms(6)
postgres.ef.repeat 183ms(6)
MS Pro 124ms(6)
mssql.pro.repeat 207ms(6)
mssql.pro.cache 170ms(6)
sqlite.pro 386ms(5)
sqlite.pro.repeat 452ms(6)
sqlite.pro.cache 511ms(6)