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

WhereRedb - DateTime.Year

Demonstrates DateTime property extraction in WhereRedb clause.
Finds objects created in the current year using DateCreate.Year.
Pro feature: server-side EXTRACT(YEAR FROM date) function.
var sw = Stopwatch.StartNew();

var currentYear = DateTime.UtcNow.Year;
Console.WriteLine($"Current Year: {currentYear}$");

// Find employees created in the current year
// Uses base field DateCreate (not Props) via WhereRedb
var query = redb.Query<EmployeeProps>()
    .WhereRedb(o => o.DateCreate.Year == currentYear)
    .Where(e => e.Age > 30)
    .Take(100);

// Uncomment to see generated SQL (contains EXTRACT):
// var sql = await query.ToSqlStringAsync();
// Console.WriteLine("Generated SQL:\n" + sql);

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .WhereRedb(o => o.DateCreate.Year == currentYear)
    .CountAsync();

sw.Stop();

var dates = results.Take(3).Select(e => e.date_create.ToString("yyyy-MM-dd"));
DateTimeYearExtractIRedbQueryable.WhereRedbDateTime.Year
PG Pro 109ms(100307)
postgres.ef 1060ms(100306)
postgres.pro.repeat 112ms(100308)
postgres.pro.cache 116ms(100309)
postgres.ef.repeat 1086ms(100307)
MS Pro 105ms(100207)
mssql.pro.repeat 59ms(100208)
mssql.pro.cache 59ms(100209)
sqlite.pro 68ms(100101)
sqlite.pro.repeat 90ms(100105)
sqlite.pro.cache 92ms(100106)

Where - Parentheses Priority

Demonstrates parentheses for operation priority in Where clause.
Calculates monthly salary (annual / 12) and filters employees earning over $7,000/month.
Pro feature: server-side arithmetic with correct operator precedence.
var sw = Stopwatch.StartNew();

// Find employees with monthly salary > $7,000
// Parentheses ensure division happens first: (Salary / 12) > 7000
var query = redb.Query<EmployeeProps>()
    .Where(e => (e.Salary / 12m) > 7000m)
    .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.Salary / 12m) > 7000m)
    .CountAsync();

sw.Stop();

var first = results.FirstOrDefault();
var monthly = first?.Props.Salary / 12m ?? 0;
ArithmeticParenthesesPriorityIRedbQueryable.Where
PG Pro 121ms(40124)
postgres.ef 1093ms(40123)
postgres.pro.repeat 80ms(40125)
postgres.pro.cache 73ms(40126)
postgres.ef.repeat 1264ms(40124)
MS Pro 128ms(40084)
mssql.pro.repeat 77ms(40085)
mssql.pro.cache 74ms(40086)
sqlite.pro 55ms(40041)
sqlite.pro.repeat 38ms(40042)
sqlite.pro.cache 36ms(40043)

Where - Nested Math

Demonstrates nested Math functions with arithmetic in Where clause.
Finds employees with salary close to $80,000 (within $10,000 range).
Pro feature: server-side ABS() with arithmetic expression inside.
var sw = Stopwatch.StartNew();

// Find employees with salary in range $70,000 - $90,000
// |Salary - 80000| < 10000 means Salary is between 70k and 90k
var query = redb.Query<EmployeeProps>()
    .Where(e => Math.Abs(e.Salary - 80000m) < 10000m)
    .Take(100);

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

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => Math.Abs(e.Salary - 80000m) < 10000m)
    .CountAsync();

sw.Stop();

var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0}");
var avgSalary = results.Any() ? results.Average(e => e.Props.Salary) : 0;
MathNestedRangeIRedbQueryable.WhereMath.Abs
PG Pro 129ms(50154)
postgres.ef 995ms(50153)
postgres.pro.repeat 96ms(50155)
postgres.pro.cache 98ms(50156)
postgres.ef.repeat 1005ms(50154)
MS Pro 121ms(50104)
mssql.pro.repeat 114ms(50105)
mssql.pro.cache 108ms(50106)
sqlite.pro 126ms(50051)
sqlite.pro.repeat 130ms(50052)
sqlite.pro.cache 115ms(50053)

TreeQuery - Expressions

Demonstrates arithmetic expressions in TreeQuery Where clause.
Finds tree nodes where 10% of budget exceeds $50,000.
Pro feature: server-side arithmetic in tree queries.
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("E160", "TreeQuery - Expressions", ExampleTier.Pro, sw.ElapsedMilliseconds,
        "No tree data found. Please run E089_TreeCreate first.");
}

// Find departments where 10% of budget > $50,000 (i.e., Budget > $500,000)
var query = redb.TreeQuery<DepartmentProps>(root.Id)
    .Where(d => d.Budget * 0.1m > 50000m)
    .Take(100);

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

var results = await query.ToListAsync();

sw.Stop();

var first = results.FirstOrDefault();
var tenPercent = first?.Props.Budget * 0.1m ?? 0;
TreeArithmeticExpressionIRedbService.TreeQueryITreeQueryable.Where
PG Pro 80ms(60)
postgres.pro.repeat 68ms(60)
postgres.pro.cache 64ms(60)
MS Pro 81ms(60)
mssql.pro.repeat 64ms(60)
mssql.pro.cache 70ms(60)
sqlite.pro 7ms(60)
sqlite.pro.repeat 7ms(60)
sqlite.pro.cache 4ms(60)

Sql.Function - COALESCE

Demonstrates Sql.Function for calling custom SQL functions.
Uses COALESCE to safely handle potentially NULL values in comparisons.
Pro feature: arbitrary SQL function calls via Sql.Function<T>().
var sw = Stopwatch.StartNew();

// COALESCE returns first non-NULL argument
// Useful for NULL-safe comparisons: COALESCE(Age, 0) > 25
var query = redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<int>("COALESCE", e.Age, 0) > 30)
    .Take(100);

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

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<int>("COALESCE", e.Age, 0) > 30)
    .CountAsync();

sw.Stop();

var ages = results.Take(5).Select(e => e.Props.Age);
Sql.FunctionCOALESCENULLSql.Function
PG Pro 108ms(85255)
postgres.ef 1023ms(85255)
postgres.pro.repeat 58ms(85255)
postgres.pro.cache 57ms(85255)
postgres.ef.repeat 1027ms(85255)
MS Pro 123ms(85170)
mssql.pro.repeat 83ms(85170)
mssql.pro.cache 81ms(85170)
sqlite.pro 113ms(85085)
sqlite.pro.repeat 145ms(85085)
sqlite.pro.cache 110ms(85085)

Sql.Function - POWER

Demonstrates Sql.Function for mathematical SQL functions.
Uses POWER to square the age and filter employees with Age^2 > 900 (Age > 30).
Pro feature: arbitrary SQL function calls via Sql.Function<T>().
var sw = Stopwatch.StartNew();

// POWER(Age, 2) > 900 means Age^2 > 900, so Age > 30
var query = redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<double>("POWER", e.Age, 2) > 900)
    .Take(100);

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

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<double>("POWER", e.Age, 2) > 900)
    .CountAsync();

sw.Stop();

var ages = results.Take(5).Select(e => $"{e.Props.Age} (^2={e.Props.Age * e.Props.Age})");
Sql.FunctionPOWERMathSql.Function
PG Pro 127ms(85255)
postgres.ef 1038ms(85255)
postgres.pro.repeat 66ms(85255)
postgres.pro.cache 63ms(85255)
postgres.ef.repeat 1054ms(85255)
MS Pro 114ms(85170)
mssql.pro.repeat 96ms(85170)
mssql.pro.cache 85ms(85170)
sqlite.pro 123ms(85085)
sqlite.pro.repeat 142ms(85085)
sqlite.pro.cache 111ms(85085)

Sql.Function - Nested

Demonstrates nested Sql.Function calls for complex SQL expressions.
Uses SQRT(Salary) > 250 to find employees with Salary > 62,500.
Pro feature: nested arbitrary SQL function calls.
var sw = Stopwatch.StartNew();

// SQRT(Salary) > 250 means Salary > 62,500
var query = redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<double>("SQRT", e.Salary) > 250)
    .Take(100);

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

var results = await query.ToListAsync();
var totalCount = await redb.Query<EmployeeProps>()
    .Where(e => Sql.Function<double>("SQRT", e.Salary) > 250)
    .CountAsync();

sw.Stop();

var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0} (√={Math.Sqrt((double)e.Props.Salary):F0})");
Sql.FunctionSQRTNestedSql.Function
PG Pro 152ms(95289)
postgres.ef 1030ms(95288)
postgres.pro.repeat 103ms(95290)
postgres.pro.cache 100ms(95291)
postgres.ef.repeat 1121ms(95289)
MS Pro 118ms(95194)
mssql.pro.repeat 91ms(95195)
mssql.pro.cache 109ms(95196)
sqlite.pro 109ms(95096)
sqlite.pro.repeat 129ms(95097)
sqlite.pro.cache 107ms(95098)

Base Fields - Single Object

Demonstrates using RedbObject base fields without Props (no props rows).
Base fields are stored directly in _objects table for fast access:
value_string, value_long, value_bool, value_double, value_datetime, value_guid, value_numeric, value_bytes.
Useful for simple objects, lookups, metadata without dynamic properties.
var sw = Stopwatch.StartNew();

// Create non-generic RedbObject with base fields only (no Props rows)
var obj = new RedbObject
{
    name = $"BaseFields_Example_{DateTime.UtcNow.Ticks}",
    value_string = "Example String Value",
    value_long = 12345,
    value_bool = true,
    value_double = 3.14159,
    value_datetime = DateTime.UtcNow,
    value_numeric = 99.99m
};

// Save - no _values table involved, only _objects
var id = await redb.SaveAsync(obj);

// Load back
var loaded = (await redb.LoadAsync(new[] { id })).FirstOrDefault();

sw.Stop();

if (loaded == null)
{
BaseFieldsRedbObjectNoPropsRedbObjectIRedbService.SaveAsync
PG Pro 80ms(1)
postgres.ef 36ms(1)
postgres.pro.repeat 82ms(1)
postgres.pro.cache 48ms(1)
postgres.ef.repeat 27ms(1)
MS Pro 107ms(1)
mssql.pro.repeat 76ms(1)
mssql.pro.cache 82ms(1)
sqlite.pro 19ms(1)
sqlite.pro.repeat 2ms(1)
sqlite.pro.cache 1ms(1)

Base Fields - Batch Operations

Demonstrates batch save/load of non-generic RedbObject with base fields.
Efficient for bulk operations on simple objects without Props.
All data stored in _objects table - no props rows.
var sw = Stopwatch.StartNew();

// Create batch of non-generic objects
var objects = new List<RedbObject>();
var batchId = DateTime.UtcNow.Ticks;

for (int i = 0; i < 1000; i++)
{
    objects.Add(new RedbObject
    {
        name = $"Batch_BaseFields_{batchId}_{i}",
        value_string = $"Item_{i}",
        value_long = i * 100,
        value_bool = i % 2 == 0
    });
}

// Batch save (cast to IRedbObject for batch API)
var ids = await redb.SaveAsync(objects.Cast<IRedbObject>());

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

sw.Stop();

if (loaded.Count != 1000)
{
BaseFieldsBatchNonGenericRedbObjectIRedbService.SaveAsync
PG Pro 124ms(1000)
postgres.ef 161ms(1000)
postgres.pro.repeat 139ms(1000)
postgres.pro.cache 143ms(1000)
postgres.ef.repeat 166ms(1000)
MS Pro 153ms(1000)
mssql.pro.repeat 192ms(1000)
mssql.pro.cache 168ms(1000)
sqlite.pro 229ms(1000)
sqlite.pro.repeat 268ms(1000)
sqlite.pro.cache 245ms(1000)

Generic with Props=null

Demonstrates using generic RedbObject<TProps> with Props=null.
Useful when you need scheme association but don't need Props values.
Only base fields are stored - Props is explicitly null.
var sw = Stopwatch.StartNew();

// Ensure scheme exists
var scheme = await redb.EnsureSchemeFromTypeAsync<EmployeeProps>();

// Create generic object but with Props=null (only base fields)
var obj = new RedbObject<EmployeeProps>
{
    name = $"GenericNullProps_{DateTime.UtcNow.Ticks}",
    scheme_id = scheme.Id,
    value_string = "MetadataOnly",
    value_long = 999,
    value_bool = true
};
obj.Props = null!; // Explicitly null - no Props values

// Save via interface (triggers non-Props save path)
var id = await redb.SaveAsync((IRedbObject)obj);

// Load as base IRedbObject (not generic)
var loaded = (await redb.LoadAsync(new[] { id })).FirstOrDefault();

sw.Stop();

if (loaded == null)
{
GenericNullPropsBaseFieldsRedbObject<TProps>IRedbService.SaveAsync
PG Pro 63ms(1)
postgres.ef 13ms(1)
postgres.pro.repeat 72ms(1)
postgres.pro.cache 68ms(1)
postgres.ef.repeat 11ms(1)
MS Pro 101ms(1)
mssql.pro.repeat 174ms(1)
mssql.pro.cache 97ms(1)
sqlite.pro 2ms(1)
sqlite.pro.repeat 1ms(1)
sqlite.pro.cache 2ms(1)